gohttpserver/httpserver/http.go

73 lines
1.7 KiB
Go
Raw Normal View History

2020-09-30 06:35:07 +00:00
package httpserver
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
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()
2020-09-30 07:48:56 +00:00
s.log.Info().Str("listenaddr", listenAddr).Msg("http begin listen")
2020-09-30 06:35:07 +00:00
if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
2020-09-30 07:48:56 +00:00
s.log.Error().Msgf("listen:%+s\n", err)
2020-09-30 06:35:07 +00:00
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 {
2020-09-30 07:48:56 +00:00
s.log.Error().Err(err).Msg("json encode error")
2020-09-30 06:35:07 +00:00
}
}
}
2020-09-30 07:48:56 +00:00
func (s *server) decodeJSON(w http.ResponseWriter, r *http.Request, v interface{}) error { // nolint
2020-09-30 06:35:07 +00:00
return json.NewDecoder(r.Body).Decode(v)
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *server) cleanupForExit() {
2020-09-30 07:48:56 +00:00
s.log.Info().Msg("cleaning up")
2020-09-30 06:35:07 +00:00
// FIXME unimplemented
// close database connections or whatever
}
func (s *server) cleanShutdown() {
// initiate clean shutdown
s.exitCode = 0
2020-09-30 07:48:56 +00:00
ctxShutdown, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
2020-09-30 06:35:07 +00:00
if err := s.httpServer.Shutdown(ctxShutdown); err != nil {
2020-09-30 07:48:56 +00:00
s.log.Error().
2020-09-30 06:35:07 +00:00
Err(err).
Msg("server clean shutdown failed")
}
2020-09-30 07:48:56 +00:00
if shutdownCancel != nil {
shutdownCancel()
}
2020-09-30 06:35:07 +00:00
s.cleanupForExit()
}