Skip to content

Commit

Permalink
refactor: rename context key variables to meaningful names
Browse files Browse the repository at this point in the history
  • Loading branch information
jeamon committed Nov 13, 2023
1 parent 29d82c1 commit bbf188d
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 29 deletions.
12 changes: 6 additions & 6 deletions api.handlers.book.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func (api *APIHandler) Index(w http.ResponseWriter, r *http.Request, _ httproute

// Status provides basics details about the application to the public users.
func (api *APIHandler) Status(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
map[string]interface{}{
Expand All @@ -32,7 +32,7 @@ func (api *APIHandler) Status(w http.ResponseWriter, r *http.Request, _ httprout

func (api *APIHandler) CreateBook(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
book := Book{}
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
err := DecodeCreateOrUpdateBookRequestBody(r, &book)
if err != nil {
api.logger.Error("failed to create book", zap.String("request.id", requestID), zap.Error(err))
Expand Down Expand Up @@ -74,7 +74,7 @@ func (api *APIHandler) CreateBook(w http.ResponseWriter, r *http.Request, _ http

//nolint:bodyclose
func (api *APIHandler) GetAllBooks(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
// this block could be moved into the TimeoutMiddleware and remove SetWriteDeadline and
// ReadWriteDeadline methods from *CustomResponseWriter object because that middleware
// is called before the stats middleware which wraps the native ResponseWriter.
Expand All @@ -101,7 +101,7 @@ func (api *APIHandler) GetAllBooks(w http.ResponseWriter, r *http.Request, _ htt
}

func (api *APIHandler) GetOneBook(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
id := ps.ByName("id")
if ok := api.idsHandler.IsValid(id, BookIDPrefix); !ok {
api.logger.Error("book id provided is not valid", zap.String("book.id", id), zap.String("request.id", requestID))
Expand Down Expand Up @@ -136,7 +136,7 @@ func (api *APIHandler) GetOneBook(w http.ResponseWriter, r *http.Request, ps htt
}

func (api *APIHandler) DeleteOneBook(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
id := ps.ByName("id")
if ok := api.idsHandler.IsValid(id, BookIDPrefix); !ok {
api.logger.Error("book id provided is not valid", zap.String("book.id", id), zap.String("request.id", requestID))
Expand Down Expand Up @@ -190,7 +190,7 @@ func (api *APIHandler) DeleteOneBook(w http.ResponseWriter, r *http.Request, ps

func (api *APIHandler) UpdateBook(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var book Book
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
err := DecodeCreateOrUpdateBookRequestBody(r, &book)
if err != nil {
api.logger.Error("failed to update book", zap.String("request.id", requestID), zap.Error(err))
Expand Down
12 changes: 6 additions & 6 deletions api.handlers.ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func GetMemStats(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

// RunGC forces the run of the garbage collector asynchronously.
func (api *APIHandler) RunGC(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
go runtime.GC()
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
Expand All @@ -82,7 +82,7 @@ func (api *APIHandler) RunGC(w http.ResponseWriter, r *http.Request, _ httproute
// FreeOSMemory forces the garbage collector to and tries to returns the memory
// back to the operating system in an asynchronous fashion.
func (api *APIHandler) FreeOSMemory(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
go debug.FreeOSMemory()
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
Expand All @@ -98,7 +98,7 @@ func (api *APIHandler) FreeOSMemory(w http.ResponseWriter, r *http.Request, _ ht
// The stats returns by this handler do not contain the ops request which triggered that.
// That is why we remove 1 from the called field value in order to match the status stats.
func (api *APIHandler) GetStatistics(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
api.stats.mu.RLock()
maintenanceModeStartedTime := api.mode.started.String()
Expand Down Expand Up @@ -131,7 +131,7 @@ func (api *APIHandler) GetStatistics(w http.ResponseWriter, r *http.Request, _ h

// GetConfigs serves current in-use configurations/settings.
func (api *APIHandler) GetConfigs(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
map[string]interface{}{
Expand All @@ -147,7 +147,7 @@ func (api *APIHandler) GetConfigs(w http.ResponseWriter, r *http.Request, _ http
// Enable the maintenance mode : /ops/maintenance?status=enable&msg=message-to-be-displayed-to-users
// Disable the maintenance mode: /ops/maintenance?status=disable
func (api *APIHandler) Maintenance(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response map[string]interface{}
var logger *zap.Logger
Expand Down Expand Up @@ -201,7 +201,7 @@ func (api *APIHandler) Maintenance(w http.ResponseWriter, r *http.Request, ps ht

// ClearBooksCache deletes all books entries from the primary storage (cache).
func (api *APIHandler) ClearBooksCache(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
go api.bookService.DeleteAll(r.Context(), requestID)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
Expand Down
12 changes: 6 additions & 6 deletions api.middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (api *APIHandler) StatsMiddleware(next httprouter.Handle) httprouter.Handle
// AddLoggerMiddleware creates a logger with pre-populated fields for each request.
func (api *APIHandler) AddLoggerMiddleware(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
requestNum := GetRequestNumberFromContext(r.Context())
logger := api.logger.With(
zap.String("request.id", requestID),
Expand All @@ -67,7 +67,7 @@ func (api *APIHandler) AddLoggerMiddleware(next httprouter.Handle) httprouter.Ha
zap.String("request.referer", r.Referer()),
)

ctx := context.WithValue(r.Context(), ContextRequestLogger, logger)
ctx := context.WithValue(r.Context(), LoggerContextKey, logger)
r = r.WithContext(ctx)
next(w, r, ps)
}
Expand All @@ -94,7 +94,7 @@ func (api *APIHandler) MaintenanceModeMiddleware(next httprouter.Handle) httprou
// new value to the request context to be used during logging as `request.num` field.
func (api *APIHandler) RequestsCounterMiddleware(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
ctx := context.WithValue(r.Context(), ContextRequestNumber, atomic.AddUint64(&api.stats.called, 1))
ctx := context.WithValue(r.Context(), RequestNumberContextKey, atomic.AddUint64(&api.stats.called, 1))
r = r.WithContext(ctx)
next(w, r, ps)
}
Expand All @@ -104,7 +104,7 @@ func (api *APIHandler) RequestsCounterMiddleware(next httprouter.Handle) httprou
func (api *APIHandler) RequestIDMiddleware(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := api.idsHandler.Generate(RequestIDPrefix)
ctx := context.WithValue(r.Context(), ContextRequestID, requestID)
ctx := context.WithValue(r.Context(), RequestIDContextKey, requestID)
r = r.WithContext(ctx)
next(w, r, ps)
}
Expand All @@ -126,7 +126,7 @@ func (api *APIHandler) PanicRecoveryMiddleware(next httprouter.Handle) httproute
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
recovery := func() {
if err := recover(); err != nil {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
api.logger.Error("panic occurred", zap.String("request.id", requestID), zap.Any("error", err))
errResp := NewAPIError(requestID, http.StatusInternalServerError, "failed to process the request.", struct{}{})
if err := WriteErrorResponse(r.Context(), w, errResp); err != nil {
Expand All @@ -144,7 +144,7 @@ func (api *APIHandler) PanicRecoveryMiddleware(next httprouter.Handle) httproute
// header to notify the final handler to not perform any action towards the client.
func (api *APIHandler) TimeoutMiddleware(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), ContextRequestID)
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
logger := api.GetLoggerFromContext(r.Context())
timeout := api.GetTimeout(r)
ctx, cancel := context.WithTimeout(r.Context(), timeout)
Expand Down
12 changes: 6 additions & 6 deletions helpers.common.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ type (
)

const (
BookIDPrefix string = "b"
RequestIDPrefix string = "r"
ContextRequestID ContextKey = "request.id"
ContextRequestNumber ContextKey = "request.number"
ConnContextKey ContextKey = "http-conn"
BookIDPrefix string = "b"
RequestIDPrefix string = "r"
RequestIDContextKey ContextKey = "request.id"
RequestNumberContextKey ContextKey = "request.number"
ConnContextKey ContextKey = "http-conn"
)

func (m missingFieldError) Error() string {
Expand All @@ -41,7 +41,7 @@ func GetValueFromContext(ctx context.Context, contextKey ContextKey) string {
// GetRequestNumberFromContext returns the request number set in
// the context. if not previously set then it returns 0.
func GetRequestNumberFromContext(ctx context.Context) uint64 {
if val := ctx.Value(ContextRequestNumber); val != nil {
if val := ctx.Value(RequestNumberContextKey); val != nil {
return val.(uint64)
}
return 0
Expand Down
4 changes: 2 additions & 2 deletions helpers.logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

const (
ContextRequestLogger ContextKey = "request.logger"
LoggerContextKey ContextKey = "request.logger"
)

// SetupLogging is a helper function that initializes the logging module.
Expand Down Expand Up @@ -68,7 +68,7 @@ func SetupLogging(config *Config, logFile *os.File, clock TickerClocker) (*zap.L
// GetLoggerFromCtx retrieves previously set logger from the context and returns it.
// If the logger can't be retrieved it will return the initial logger of the App.
func (api *APIHandler) GetLoggerFromContext(ctx context.Context) *zap.Logger {
value := ctx.Value(ContextRequestLogger)
value := ctx.Value(LoggerContextKey)
if value != nil {
return value.(*zap.Logger)
}
Expand Down
6 changes: 3 additions & 3 deletions tests.middlewares_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func TestMaintenanceModeMiddleware(t *testing.T) {
ts := NewMockClocker().Now()
api.mode.started = ts
api.mode.reason = "ongoing maintenance."
req = req.WithContext(context.WithValue(req.Context(), ContextRequestID, "abc"))
req = req.WithContext(context.WithValue(req.Context(), RequestIDContextKey, "abc"))
wrapped := api.MaintenanceModeMiddleware(handler)
wrapped(w, req, nil)
// target handler will not be called but the maintenance handler must kick-in.
Expand All @@ -147,7 +147,7 @@ func TestRequestIDMiddleware(t *testing.T) {
var id string
handler := func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
called = true
id = GetValueFromContext(req.Context(), ContextRequestID)
id = GetValueFromContext(req.Context(), RequestIDContextKey)
}
wrapped := api.RequestIDMiddleware(handler)
wrapped(w, req, nil)
Expand All @@ -166,7 +166,7 @@ func TestAddLoggerMiddleware(t *testing.T) {
var value interface{}
handler := func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
called = true
value = req.Context().Value(ContextRequestLogger)
value = req.Context().Value(LoggerContextKey)
}
wrapped := api.AddLoggerMiddleware(handler)
wrapped(w, req, nil)
Expand Down

0 comments on commit bbf188d

Please sign in to comment.