-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhttp_server.go
61 lines (48 loc) · 1.54 KB
/
http_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
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
"time"
)
type httpServer struct {
server *http.Server
}
func NewServer(host, port string, keycloak *keycloak) *httpServer {
// create a root router
router := mux.NewRouter()
// add a subrouter based on matcher func
// note, routers are processed one by one in order, so that if one of the routing matches other won't be processed
noAuthRouter := router.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
return r.Header.Get("Authorization") == ""
}).Subrouter()
// add one more subrouter for the authenticated service methods
authRouter := router.MatcherFunc(func(r *http.Request, rm *mux.RouteMatch) bool {
return true
}).Subrouter()
// instantiate a new controller which is supposed to serve our routes
controller := newController(keycloak)
// map url routes to controller's methods
noAuthRouter.HandleFunc("/login", func(writer http.ResponseWriter, request *http.Request) {
controller.login(writer, request)
}).Methods("POST")
authRouter.HandleFunc("/docs", func(writer http.ResponseWriter, request *http.Request) {
controller.getDocs(writer, request)
}).Methods("GET")
// apply middleware
mdw := newMiddleware(keycloak)
authRouter.Use(mdw.verifyToken)
// create a server object
s := &httpServer{
server: &http.Server{
Addr: fmt.Sprintf("%s:%s", host, port),
Handler: router,
WriteTimeout: time.Hour,
ReadTimeout: time.Hour,
},
}
return s
}
func (s *httpServer) listen() error {
return s.server.ListenAndServe()
}