forked from portainer/portainer
/
withitem.go
59 lines (48 loc) · 1.61 KB
/
withitem.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package middlewares
import (
"context"
"errors"
"net/http"
bolterrors "github.com/cloudogu/portainer-ce/api/dataservices/errors"
"github.com/gorilla/mux"
httperror "github.com/portainer/libhttp/error"
"github.com/portainer/libhttp/request"
)
type ItemContextKey string
type ItemGetter[TId ~int, TObject any] func(id TId) (*TObject, error)
func WithItem[TId ~int, TObject any](getter ItemGetter[TId, TObject], idParam string, contextKey ItemContextKey) mux.MiddlewareFunc {
if idParam == "" {
idParam = "id"
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
itemId, err := request.RetrieveNumericRouteVariableValue(req, idParam)
if err != nil {
httperror.WriteError(rw, http.StatusBadRequest, "Invalid identifier route variable", err)
return
}
item, err := getter(TId(itemId))
if err != nil {
statusCode := http.StatusInternalServerError
if err == bolterrors.ErrObjectNotFound {
statusCode = http.StatusNotFound
}
httperror.WriteError(rw, statusCode, "Unable to find a object with the specified identifier inside the database", err)
return
}
ctx := context.WithValue(req.Context(), contextKey, item)
next.ServeHTTP(rw, req.WithContext(ctx))
})
}
}
func FetchItem[T any](request *http.Request, contextKey string) (*T, error) {
contextData := request.Context().Value(contextKey)
if contextData == nil {
return nil, errors.New("unable to find item in request context")
}
item, ok := contextData.(*T)
if !ok {
return nil, errors.New("unable to cast context item")
}
return item, nil
}