go-jamming/app/server.go

48 lines
979 B
Go
Raw Normal View History

2021-04-07 10:06:16 +02:00
package app
import (
2021-04-11 13:03:41 +02:00
"brainbaking.com/go-jamming/rest"
2021-04-11 16:12:03 +02:00
"github.com/MagnusFrater/helmet"
2021-04-07 10:06:16 +02:00
"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
}
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"]) {
2021-04-11 13:03:41 +02:00
rest.Unauthorized(w)
return
}
h(w, r)
}
2021-04-07 10:06:16 +02:00
}
func Start() {
r := mux.NewRouter()
config := common.Configure()
config.SetupDataDirs()
2021-04-11 16:12:03 +02:00
helmet := helmet.Default()
server := &server{router: r, conf: config}
2021-04-07 10:06:16 +02:00
server.routes()
http.Handle("/", r)
2021-04-11 15:42:44 +02:00
r.Use(LoggingMiddleware)
2021-04-11 16:12:03 +02:00
r.Use(helmet.Secure)
2021-04-11 15:42:44 +02:00
r.Use(NewRateLimiter(5, 10).Middleware)
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
}