RestApiv2/internal/restserver/restserver.go

75 lines
1.5 KiB
Go

package restserver
import (
"net/http"
"git.ukamnya.ru/stulyaganov/RestApiv2/internal/bd"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/sirupsen/logrus"
)
const (
ContextKeyUser = iota
defaultPermLvl = 1
writerPermLvl = 2
adminPermLvl = 3
)
type RestServer struct {
config *Config
logger *logrus.Logger
router *mux.Router
db *bd.Bd
}
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
}
if err := r.configurebd(); err != nil {
return err
}
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)
r.configureRouterFilms()
r.configureRouterSiries()
r.configureRouterUser()
r.logger.Info("Starting Server")
r.logger.Info("Listen server on ", r.config.BindPort, " Port")
return http.ListenAndServe(r.config.BindPort, corsHendler)
}
func (r *RestServer) configureLogger() error {
level, err := logrus.ParseLevel(r.config.LogLevel)
if err != nil {
return err
}
r.logger.SetLevel(level)
return nil
}
func (r *RestServer) configurebd() error {
dataBase := bd.New(r.config.DB)
if err := dataBase.Open(); err != nil {
return err
}
r.db = dataBase
return nil
}