-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
53 lines (45 loc) · 1.17 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
package server
import (
"encoding/json"
"log"
"net/http"
"github.com/LucaCtt/thelist/common/client"
"github.com/LucaCtt/thelist/common/store"
"github.com/LucaCtt/thelist/errors"
"github.com/go-chi/chi"
)
// Server is an http server which serves a REST API for shows.
type Server struct {
store store.Store
client client.Client
router chi.Router
}
// New creates a new Server with the given dependencies.
func New(s store.Store, c client.Client) *Server {
server := &Server{
store: s,
client: c,
router: chi.NewRouter(),
}
server.routes()
return server
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *Server) respond(w http.ResponseWriter, r *http.Request, data interface{}, status int) {
w.WriteHeader(status)
if data != nil {
if err := json.NewEncoder(w).Encode(data); err != nil {
panic(err)
}
}
}
func (s *Server) decode(w http.ResponseWriter, r *http.Request, out interface{}) error {
return json.NewDecoder(r.Body).Decode(out)
}
func (s *Server) error(w http.ResponseWriter, r *http.Request, e error) {
code := int(errors.Code(e))
http.Error(w, http.StatusText(code), code)
log.Print(e)
}