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.MongodbStorage } 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)) bookmarkRouter := apiRouter.PathPrefix("/bookmark").Subrouter() bookmarkRouter.Use(s.AuthorizedOnly) bookmarkRouter.Path("").Methods("GET").HandlerFunc(MakeHTTPHandler(s.handleGetBookmarks)) bookmarkRouter.Path("").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleNewBookmark)) bookmarkRouter.Path("").Methods("PUT").HandlerFunc(MakeHTTPHandler(s.handleUpdateBookmark)) bookmarkRouter.Path("/{id}").Methods("DELETE").HandlerFunc(MakeHTTPHandler(s.handleDeleteBookmark)) bookmarkRouter.Path("/last").HandlerFunc(MakeHTTPHandler(s.handleGetLastBookmarks)) bookmarkRouter.Path("/last/{count}").HandlerFunc(MakeHTTPHandler(s.handleGetLastBookmarks)) bookmarkRouter.Path("/random").HandlerFunc(MakeHTTPHandler(s.handleGetRandomBookmarks)) bookmarkRouter.Path("/random/{count}").HandlerFunc(MakeHTTPHandler(s.handleGetRandomBookmarks)) folderRouter := apiRouter.PathPrefix("/f").Subrouter() folderRouter.Use(s.AuthorizedOnly) folderRouter.Path("/{id}").Methods("GET").HandlerFunc(MakeHTTPHandler(s.handleGetFolder)) folderRouter.Path("").Methods("GET").HandlerFunc(MakeHTTPHandler(s.handleGetFolder)) folderRouter.Path("").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleNewFolder)) folderRouter.Path("").Methods("PUT").HandlerFunc(MakeHTTPHandler(s.handleUpdateFolder)) folderRouter.Path("/{id}").Methods("DELETE").HandlerFunc(MakeHTTPHandler(s.handleDeleteFolder)) folderRouter.Path("/{name}").HandlerFunc(MakeHTTPHandler(s.handleGetFolder)) r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/"))) }