1
package elemental
2

3
import "net/http"
4

5
// Namespacer is the interface that any namespace extraction/injection
6
// implementation should support.
7
type Namespacer interface {
8
	Extract(r *http.Request) (string, error)
9
	Inject(r *http.Request, namespace string) error
10
}
11

12
var (
13
	namespacer = Namespacer(&defaultNamespacer{})
14
)
15

16
type defaultNamespacer struct{}
17

18
// defaultExtractor will retrieve the namespace value from the header X-Namespace.
19
func (d *defaultNamespacer) Extract(r *http.Request) (string, error) {
20 14
	return r.Header.Get("X-Namespace"), nil
21
}
22

23
// defaultInjector will set the namespace as an HTTP header.
24
func (d *defaultNamespacer) Inject(r *http.Request, namespace string) error {
25 14
	if r.Header == nil {
26 14
		r.Header = http.Header{}
27
	}
28 14
	r.Header.Set("X-Namespace", namespace)
29 14
	return nil
30
}
31

32
// SetNamespacer will configure the package. It must be only called once
33
// and it is global for the package.
34
func SetNamespacer(custom Namespacer) {
35 14
	namespacer = custom
36
}
37

38
// GetNamespacer retrieves the configured namespacer.
39
func GetNamespacer() Namespacer {
40 14
	return namespacer
41
}

Read our documentation on viewing source code .

Loading