Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
config: add config middleware and rig config loading
config/config.go | 22 ++++++++++++++++++++++ config/middleware.go | 40 ++++++++++++++++++++++++++++++++++++++++
diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000000000000000000000000000000000000..e42e54a917b0e092daa67a7017fb849042410bf7 --- /dev/null +++ b/config/config.go @@ -0,0 +1,22 @@ +package config + +import ( + "log" + + "github.com/vaughan0/go-ini" +) + +func LoadConfig() ini.File { + var ( + config ini.File + err error + ) + + config, err = ini.LoadFile("config.ini") + + if err != nil { + log.Fatalf("Failed to load config file from %v", err) + } + + return config +} diff --git a/config/middleware.go b/config/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..0b45893b137449d99e237d01f9b2ef745d7cd0d2 --- /dev/null +++ b/config/middleware.go @@ -0,0 +1,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 +}