From 0197d9cd493b5785bca05f476856540ec64da64a Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 7 Aug 2021 20:38:37 -0600 Subject: split configuration parsing out into separate packages, split api out as well --- srv/api/utils.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 srv/api/utils.go (limited to 'srv/api/utils.go') diff --git a/srv/api/utils.go b/srv/api/utils.go new file mode 100644 index 0000000..8e2a63b --- /dev/null +++ b/srv/api/utils.go @@ -0,0 +1,60 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/mediocregopher/mediocre-go-lib/v2/mlog" +) + +type loggerCtxKey int + +func setRequestLogger(r *http.Request, logger *mlog.Logger) *http.Request { + ctx := r.Context() + ctx = context.WithValue(ctx, loggerCtxKey(0), logger) + return r.WithContext(ctx) +} + +func getRequestLogger(r *http.Request) *mlog.Logger { + ctx := r.Context() + logger, _ := ctx.Value(loggerCtxKey(0)).(*mlog.Logger) + if logger == nil { + logger = mlog.Null + } + return logger +} + +func jsonResult(rw http.ResponseWriter, r *http.Request, v interface{}) { + b, err := json.Marshal(v) + if err != nil { + internalServerError(rw, r, err) + return + } + b = append(b, '\n') + + rw.Header().Set("Content-Type", "application/json") + rw.Write(b) +} + +func badRequest(rw http.ResponseWriter, r *http.Request, err error) { + getRequestLogger(r).Warn(r.Context(), "bad request", err) + + rw.WriteHeader(400) + jsonResult(rw, r, struct { + Error string `json:"error"` + }{ + Error: err.Error(), + }) +} + +func internalServerError(rw http.ResponseWriter, r *http.Request, err error) { + getRequestLogger(r).Error(r.Context(), "internal server error", err) + + rw.WriteHeader(500) + jsonResult(rw, r, struct { + Error string `json:"error"` + }{ + Error: "internal server error", + }) +} -- cgit v1.2.3