-
Notifications
You must be signed in to change notification settings - Fork 15
/
server.go
67 lines (59 loc) · 1.27 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package http
import (
"context"
"log"
"net/http"
"github.com/akornatskyy/goext/errorstate"
"github.com/akornatskyy/goext/httpjson"
"github.com/akornatskyy/scheduler/core"
"github.com/akornatskyy/scheduler/domain"
)
const (
addr = ":8080"
)
type Server struct {
Service *core.Service
srv *http.Server
}
func (s *Server) Start() {
s.srv = &http.Server{
Addr: addr,
Handler: s.Routes(),
}
go func() {
log.Println("http started")
if err := s.srv.ListenAndServe(); err != nil {
switch err {
case http.ErrServerClosed:
log.Println("http stopped")
default:
log.Printf("http serve: %s", err)
}
}
}()
log.Printf("http listening on %s", s.srv.Addr)
}
func (s *Server) Stop() {
if err := s.srv.Shutdown(context.Background()); err != nil {
log.Printf("shutdown: %s", err)
}
if err := s.srv.Close(); err != nil {
log.Printf("close: %s", err)
}
}
func writeError(w http.ResponseWriter, err error) {
switch err {
case domain.ErrNotFound:
w.WriteHeader(http.StatusNotFound)
case domain.ErrConflict:
w.WriteHeader(http.StatusConflict)
default:
switch err.(type) {
case *errorstate.ErrorState:
httpjson.Encode(w, err, http.StatusBadRequest)
default:
log.Printf("ERR: %s", err)
w.WriteHeader(http.StatusServiceUnavailable)
}
}
}