// Package web provides HTTP server related functions and structures. package web import ( "context" "net/http" "go.uber.org/zap" ) // NewHTTPServer takes a database connection and a logger as parameters // It returns a pointer to a Server struct func NewHTTPServer(log *zap.Logger) *Server { router := http.NewServeMux() services := make(map[string]interface{}) return &Server{ Log: log, Router: router, Services: services, } } // Run starts the HTTP server on port passed as parameter (":12345"). func (s *Server) Run(port string) { http.ListenAndServe(port, s.Router) } // AddRoute adds a new route to the server's router. // Adding server resources in context func (s *Server) AddRoute(pattern string, handlefunc http.HandlerFunc) { s.Router.Handle(pattern, s.WithServerContext(handlefunc)) } // WithServerContext adds the logger and services to the request context. func (s *Server) WithServerContext(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := context.WithValue(r.Context(), "log", s.Log) ctx = context.WithValue(ctx, "services", s.Services) next.ServeHTTP(w, r.WithContext(ctx)) } } func GetServerContext(r *http.Request) (*zap.Logger, map[string]interface{}) { services := r.Context().Value("services").(map[string]interface{}) log := r.Context().Value("log").(*zap.Logger) return log, services }