51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package server
|
|
|
|
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()
|
|
|
|
s.log.Info().Str("listenaddr", listenAddr).Msg("http begin listen")
|
|
if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
s.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 {
|
|
s.log.Error().Err(err).Msg("json encode error")
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *server) decodeJSON(w http.ResponseWriter, r *http.Request, v interface{}) error { // nolint
|
|
return json.NewDecoder(r.Body).Decode(v)
|
|
}
|
|
|
|
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
s.router.ServeHTTP(w, r)
|
|
}
|