This repository has been archived by the owner on Apr 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.go
85 lines (66 loc) · 1.74 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package server
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi"
"github.com/go-kit/kit/log"
"github.com/marcusolsson/pathfinder"
)
// Server holds the dependencies for a HTTP server.
type Server struct {
Paths pathfinder.PathService
Logger log.Logger
router chi.Router
}
// New returns a new HTTP server.
func New(ps pathfinder.PathService, logger log.Logger) *Server {
s := &Server{
Paths: ps,
Logger: logger,
}
r := chi.NewRouter()
r.Use(accessControl)
r.Get("/paths", s.shortestPaths)
r.Method("GET", "/docs", http.StripPrefix("/docs/", http.FileServer(http.Dir("api"))))
s.router = r
return s
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *Server) shortestPaths(w http.ResponseWriter, r *http.Request) {
var (
from = r.URL.Query().Get("from")
to = r.URL.Query().Get("to")
)
paths, err := s.Paths.ShortestPath(from, to)
if err != nil {
if err == pathfinder.ErrInvalidArgument {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusInternalServerError)
return
}
response := struct {
Paths interface{} `json:"paths"`
}{
Paths: paths,
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(response); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func accessControl(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type")
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}