dinheiro

ref: master

config/middleware.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
package config

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

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

var configCtxKey = &contextKey{"config"}

type contextKey struct {
	name string
}

func Middleware(config ini.File) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
			ctx := Context(req.Context(), config)
			req = req.WithContext(ctx)

			next.ServeHTTP(writer, req)
		})
	}
}

func Context(ctx context.Context, config ini.File) context.Context {
	return context.WithValue(ctx, configCtxKey, config)
}

func ForContext(ctx context.Context) ini.File {
	raw, ok := ctx.Value(configCtxKey).(ini.File)

	if !ok {
		panic(errors.New("Invalid config context"))
	}

	return raw
}