package httpserver import ( "context" "encoding/json" "fmt" "net/http" "time" "github.com/rs/zerolog/log" ) func (s *server) serveUntilShutdown() { listenAddr := fmt.Sprintf(":%d", s.port) s.httpServer = &http.Server{ Addr: listenAddr, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, Handler: s, } // add routes // this does any necessary setup in each handler s.routes() log.Info().Str("listenaddr", listenAddr).Msg("http begin listen") if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Error().Msgf("listen:%+s\n", err) if s.cancelFunc != nil { s.cancelFunc() } } } func (s *server) respondJSON(w http.ResponseWriter, r *http.Request, data interface{}, status int) { w.WriteHeader(status) w.Header().Set("Content-Type", "application/json") if data != nil { err := json.NewEncoder(w).Encode(data) if err != nil { log.Error().Err(err).Msg("json encode error") } } } func (s *server) decodeJSON(w http.ResponseWriter, r *http.Request, v interface{}) error { return json.NewDecoder(r.Body).Decode(v) } func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // FIXME logging or any other general purpose middleware here s.router.ServeHTTP(w, r) } func (s *server) cleanupForExit() { log.Info().Msg("cleaning up") // FIXME unimplemented // close database connections or whatever } func (s *server) cleanShutdown() { // initiate clean shutdown s.exitCode = 0 ctxShutdown, _ := context.WithTimeout(context.Background(), 5*time.Second) if err := s.httpServer.Shutdown(ctxShutdown); err != nil { log.Error(). Err(err). Msg("server clean shutdown failed") } s.cleanupForExit() }