Nashboard/server/server.go

45 lines
1.3 KiB
Go
Raw Normal View History

2022-12-11 02:05:03 +03:00
package server
import (
"net/http"
"git.nefrace.ru/nefrace/nashboard/storage"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type Server struct {
Host string
Mux *mux.Router
Db storage.Storage
}
var ErrUnauthorized ApiError = ApiError{Status: http.StatusUnauthorized, Err: "Unauthorized"}
var ErrBadRequest ApiError = ApiError{Status: http.StatusBadRequest, Err: "bad request"}
var anon storage.User = storage.User{
Id: primitive.ObjectID{},
Username: "Anonymous",
IsAdmin: false,
}
func (s Server) InitHandlers() {
r := s.Mux
r.Use(s.Logger)
r.Use(s.UserInContext)
apiRouter := r.PathPrefix("/api").Subrouter()
authRouter := apiRouter.PathPrefix("/auth").Subrouter()
authRouter.Path("/reg").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleRegister))
authRouter.Path("/login").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleLogin))
authRouter.Path("/logout").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleLogout))
userRouter := apiRouter.PathPrefix("/user").Subrouter()
userRouter.Use(s.AuthorizedOnly)
userRouter.Use(s.AuthorizedOnly)
userRouter.Path("/me").HandlerFunc(MakeHTTPHandler(s.handleGetMe))
userRouter.Path("/all").HandlerFunc(MakeHTTPHandler(s.handleAllUsers))
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
}