go-jamming/app/server.go

46 lines
1.1 KiB
Go
Raw Normal View History

2021-04-07 10:06:16 +02:00
package app
import (
"net/http"
"strconv"
2021-04-07 10:06:16 +02:00
2021-04-09 18:04:04 +02:00
"brainbaking.com/go-jamming/common"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
2021-04-07 10:06:16 +02:00
)
type server struct {
router *mux.Router
conf *common.Config
}
// mimicing NotFound: https://golang.org/src/net/http/server.go?s=64787:64830#L2076
func unauthorized(w http.ResponseWriter, r *http.Request) { http.Error(w, "401 unauthorized", http.StatusUnauthorized) }
func (s *server) authorizedOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if vars["token"] != s.conf.Token || !s.conf.IsAnAllowedDomain(vars["domain"]) {
unauthorized(w, r)
return
}
h(w, r)
}
2021-04-07 10:06:16 +02:00
}
func Start() {
r := mux.NewRouter()
2021-04-08 12:16:33 +02:00
config := common.Configure()
config.SetupDataDirs()
server := &server{router: r, conf: config}
2021-04-07 10:06:16 +02:00
server.routes()
http.Handle("/", r)
r.Use(loggingMiddleware)
2021-04-07 10:06:16 +02:00
log.Info().Int("port", server.conf.Port).Msg("Serving...")
http.ListenAndServe(":" + strconv.Itoa(server.conf.Port), nil)
2021-04-07 10:06:16 +02:00
}