gohttpserver/internal/server/http.go

51 lines
1.2 KiB
Go
Raw Normal View History

package server
2020-09-30 06:35:07 +00:00
import (
"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)
}