API: Update endpoints to return HTTP 201 when a new resource was created

Signed-off-by: Michael Mayer <michael@photoprism.app>
This commit is contained in:
Michael Mayer 2025-10-20 16:46:59 +02:00
parent ddc37e08ab
commit ce304abd2c
12 changed files with 194 additions and 30 deletions

View file

@ -0,0 +1,60 @@
package header
import (
"strings"
"github.com/gin-gonic/gin"
)
// SetLocation adds a Location header with a relative path based on the provided segments.
// When the first segment is non-empty it is treated as the base path;
// otherwise the request URL path is used.
func SetLocation(c *gin.Context, segments ...string) {
// Return if context is missing.
if c == nil {
return
}
base := ""
if len(segments) > 0 && segments[0] != "" {
base = segments[0]
segments = segments[1:]
} else if c.Request != nil && c.Request.URL != nil {
base = c.Request.URL.Path
}
// Return if base is missing.
if base == "" {
return
}
// Compose redirect location string.
prefixSlash := strings.HasPrefix(base, "/")
base = strings.Trim(base, "/")
parts := make([]string, 0, 1+len(segments))
if base != "" {
parts = append(parts, base)
}
for _, segment := range segments {
segment = strings.Trim(segment, "/")
if segment == "" {
continue
}
parts = append(parts, segment)
}
location := strings.Join(parts, "/")
if prefixSlash {
location = "/" + location
}
// Add Location header to response.
if location == "" && prefixSlash {
c.Header(Location, "/")
} else {
c.Header(Location, location)
}
}

View file

@ -0,0 +1,43 @@
package header
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestSetLocationWithBase(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/albums", nil)
SetLocation(c, "/api/v1/albums", "abc123")
assert.Equal(t, "/api/v1/albums/abc123", c.Writer.Header().Get(Location))
}
func TestSetLocationUsesRequestPath(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/services", nil)
SetLocation(c, "", "99")
assert.Equal(t, "/api/v1/services/99", c.Writer.Header().Get(Location))
}
func TestSetLocationTrimsSegments(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/markers/", nil)
SetLocation(c, "/api/v1/markers/", "/m1/")
assert.Equal(t, "/api/v1/markers/m1", c.Writer.Header().Get(Location))
}
func TestSetLocationEmpty(t *testing.T) {
SetLocation(nil)
}