Fix various issues during portmaster development

This commit is contained in:
Daniel 2019-01-24 15:23:35 +01:00
parent a943e3315f
commit 358e684909
5 changed files with 92 additions and 41 deletions

View file

@ -9,20 +9,18 @@ import (
)
var (
additionalRoutes map[string]http.Handler
router = mux.NewRouter()
)
// RegisterAdditionalRoute registers an additional route with the API endoint.
func RegisterAdditionalRoute(path string, handler http.Handler) {
if additionalRoutes == nil {
additionalRoutes = make(map[string]http.Handler)
}
additionalRoutes[path] = handler
// RegisterHandleFunc registers an additional handle function with the API endoint.
func RegisterHandleFunc(path string, handleFunc func(http.ResponseWriter, *http.Request)) *mux.Route {
return router.HandleFunc(path, handleFunc)
}
// RequestLogger is a logging middleware
func RequestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Tracef("api request: %s ___ %s", r.RemoteAddr, r.RequestURI)
ew := NewEnrichedResponseWriter(w)
next.ServeHTTP(ew, r)
log.Infof("api request: %s %d %s", r.RemoteAddr, ew.Status, r.RequestURI)
@ -31,20 +29,13 @@ func RequestLogger(next http.Handler) http.Handler {
// Serve starts serving the API endpoint.
func Serve() {
router := mux.NewRouter()
// router.HandleFunc("/api/database/v1", startDatabaseAPI)
for path, handler := range additionalRoutes {
router.Handle(path, handler)
}
router.Use(RequestLogger)
http.Handle("/", router)
http.HandleFunc("/api/database/v1", startDatabaseAPI)
mainMux := http.NewServeMux()
mainMux.Handle("/", router) // net/http pattern matching /*
mainMux.HandleFunc("/api/database/v1", startDatabaseAPI) // net/http pattern matching only this exact path
address := getListenAddress()
log.Infof("api: starting to listen on %s", address)
log.Errorf("api: failed to listen on %s: %s", address, http.ListenAndServe(address, nil))
log.Errorf("api: failed to listen on %s: %s", address, http.ListenAndServe(address, mainMux))
}