-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
67 lines (57 loc) · 1.57 KB
/
http.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 market
import (
"net/http"
"strings"
"github.com/google/uuid"
"github.com/henvic/httpretty"
"github.com/plifk/market/internal/api"
"github.com/plifk/market/internal/frontend"
)
// ServerHTTP handles HTTP requests to the market system.
// It serves API, admin, and web pages based on the request Host address.
func (s *System) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Request-ID") == "" {
r.Header.Set("X-Request-ID", uuid.New().String())
}
var h http.Handler
switch {
case strings.HasPrefix(r.Host, "api."):
h = s.api
case strings.HasPrefix(r.Host, "www."):
h = s.frontend
default:
h = s.notFound
}
h.ServeHTTP(w, r)
}
func (s *System) httpHandlers() {
settings := s.core.Settings
s.httpServer = &http.Server{
Addr: settings.HTTPAddress,
Handler: s.core.CSRFProtection, // This CSRF middleware injects the HTTP entrypoint.
}
if settings.Debug {
s.httpServer.Handler = httpLogger().Middleware(s.httpServer.Handler)
}
s.api = &api.Router{}
s.api.Load(s.Modules)
s.frontend = &frontend.Router{}
s.frontend.Load(s.Modules)
}
func httpLogger() *httpretty.Logger {
l := &httpretty.Logger{
Colors: true,
Formatters: []httpretty.Formatter{&httpretty.JSONFormatter{}},
}
l.SetFilter(func(req *http.Request) (skip bool, err error) {
if !strings.HasPrefix(req.URL.Host, "api.") {
return true, nil
}
return false, nil
})
return l
}
type notFoundHandler struct{}
func (h notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "market server: page or endpoint not found", 404)
}