/
model.go
86 lines (74 loc) · 2.67 KB
/
model.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2018 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package httpcontext
import (
"context"
"fmt"
"net/http"
"github.com/juju/names/v5"
)
// ImpliedModelHandler is an http.Handler that associates requests that
// it handles with a specified model UUID. The model UUID can then be
// extracted using the RequestModel function in this package.
type ImpliedModelHandler struct {
http.Handler
ModelUUID string
}
// ServeHTTP is part of the http.Handler interface.
func (h *ImpliedModelHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx := context.WithValue(req.Context(), modelKey{}, h.ModelUUID)
req = req.WithContext(ctx)
h.Handler.ServeHTTP(w, req)
}
// QueryModelHandler is an http.Handler that associates requests that
// it handles with a model UUID extracted from a specified query parameter.
// The model UUID can then be extracted using the RequestModel function
// in this package.
type QueryModelHandler struct {
http.Handler
Query string
}
// ServeHTTP is part of the http.Handler interface.
func (h *QueryModelHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
modelUUID := req.URL.Query().Get(h.Query)
validateModelAndServe(h.Handler, modelUUID, w, req)
}
// BucketModelHandler is an http.Handler that associates requests that
// it handles with a model UUID extracted from a specified query parameter that
// must be the objects storage :bucket which is formatted 'model-{modelUUID}'.
// The model UUID can then be extracted using the RequestModel function
// in this package.
type BucketModelHandler struct {
http.Handler
Query string
}
// ServeHTTP is part of the http.Handler interface.
func (h *BucketModelHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
modelUUID := req.URL.Query().Get(h.Query)
validateModelAndServe(h.Handler, modelUUID, w, req)
}
func validateModelAndServe(handler http.Handler, modelUUID string, w http.ResponseWriter, req *http.Request) {
if modelUUID != "" {
if !names.IsValidModel(modelUUID) {
http.Error(w,
fmt.Sprintf("invalid model UUID %q", modelUUID),
http.StatusBadRequest,
)
return
}
ctx := context.WithValue(req.Context(), modelKey{}, modelUUID)
req = req.WithContext(ctx)
}
handler.ServeHTTP(w, req)
}
type modelKey struct{}
// RequestModelUUID returns the model UUID associated with this request
// if there is one, or the empty string otherwise. No attempt is made
// to validate the model UUID; QueryModelHandler does this, and
// ImpliedModelHandler should always be supplied with a valid UUID.
func RequestModelUUID(req *http.Request) string {
if value := req.Context().Value(modelKey{}); value != nil {
return value.(string)
}
return ""
}