2022-12-07 21:29:01 +03:00
|
|
|
package restserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2023-03-31 20:08:38 +03:00
|
|
|
"git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd"
|
2022-12-07 21:29:01 +03:00
|
|
|
"github.com/gorilla/mux"
|
2023-05-02 11:02:06 +03:00
|
|
|
"github.com/rs/cors"
|
2022-12-07 21:29:01 +03:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2023-04-14 17:35:25 +03:00
|
|
|
const (
|
2023-05-08 23:16:20 +03:00
|
|
|
ContextKeyUser = iota
|
|
|
|
defaultPermLvl = 1
|
|
|
|
writerPermLvl = 2
|
|
|
|
adminPermLvl = 3
|
|
|
|
ContextKeyPayload = 4
|
2023-04-14 17:35:25 +03:00
|
|
|
)
|
|
|
|
|
2022-12-07 21:29:01 +03:00
|
|
|
type RestServer struct {
|
|
|
|
config *Config
|
|
|
|
logger *logrus.Logger
|
|
|
|
router *mux.Router
|
2022-12-12 20:34:00 +03:00
|
|
|
db *bd.Bd
|
2022-12-07 21:29:01 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func New(config *Config) *RestServer {
|
|
|
|
return &RestServer{
|
|
|
|
config: config,
|
|
|
|
logger: logrus.New(),
|
|
|
|
router: mux.NewRouter(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RestServer) Start() error {
|
|
|
|
if err := r.configureLogger(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-12-12 20:34:00 +03:00
|
|
|
if err := r.configurebd(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-05-02 11:02:06 +03:00
|
|
|
corsHendler := cors.New(cors.Options{
|
|
|
|
AllowedOrigins: []string{"http://localhost:3000"},
|
|
|
|
AllowedHeaders: []string{"Content-Type", "Authorization", "Set-Cookie"},
|
|
|
|
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions, http.MethodDelete, http.MethodPut},
|
|
|
|
AllowCredentials: true,
|
|
|
|
}).Handler(r.router)
|
2023-01-07 14:19:53 +03:00
|
|
|
r.configureRouterFilms()
|
2023-03-30 23:12:39 +03:00
|
|
|
r.configureRouterSiries()
|
2023-01-07 14:19:53 +03:00
|
|
|
r.configureRouterUser()
|
2022-12-07 21:29:01 +03:00
|
|
|
|
|
|
|
r.logger.Info("Starting Server")
|
|
|
|
r.logger.Info("Listen server on ", r.config.BindPort, " Port")
|
2023-05-02 11:02:06 +03:00
|
|
|
return http.ListenAndServe(r.config.BindPort, corsHendler)
|
2022-12-07 21:29:01 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RestServer) configureLogger() error {
|
|
|
|
level, err := logrus.ParseLevel(r.config.LogLevel)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
r.logger.SetLevel(level)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-12-12 20:34:00 +03:00
|
|
|
func (r *RestServer) configurebd() error {
|
|
|
|
dataBase := bd.New(r.config.DB)
|
|
|
|
if err := dataBase.Open(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
r.db = dataBase
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|