~bigbes/core-go

ref: fa27910a9402d8f911425a9560f39bfba4583c2d core-go/config/middleware.go -rw-r--r-- 1.1 KiB
fa27910a — Drew DeVault Add prometheus SQL connection stats 3 years ago
                                                                                
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
package config

import (
	"context"
	"errors"
	"net/http"

	"github.com/vaughan0/go-ini"
)

var configCtxKey = &contextKey{"config"}
var serviceCtxKey = &contextKey{"name"}

type contextKey struct {
	name string
}

func Middleware(conf ini.File, service string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := Context(r.Context(), conf, service)
			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)
		})
	}
}

func Context(ctx context.Context, conf ini.File, service string) context.Context {
	svc := service
	ctx = context.WithValue(ctx, configCtxKey, conf)
	ctx = context.WithValue(ctx, serviceCtxKey, &svc)
	return ctx
}

func ForContext(ctx context.Context) ini.File {
	raw, ok := ctx.Value(configCtxKey).(ini.File)
	if !ok {
		panic(errors.New("Invalid config context"))
	}
	return raw
}

func ServiceName(ctx context.Context) string {
	raw, ok := ctx.Value(serviceCtxKey).(*string)
	if !ok {
		panic(errors.New("Invalid service config context"))
	}
	return *raw
}