update: use env file to config server

This commit is contained in:
Kenta420-Poom 2023-09-20 10:39:11 +07:00
parent 59407840cd
commit d8f9858ea0
8 changed files with 541 additions and 12 deletions

View file

@ -9,37 +9,72 @@ import (
"net/url"
"os"
"os/exec"
"recipe-manager/config"
"recipe-manager/data"
"recipe-manager/routers"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
"github.com/spf13/viper"
)
func loadConfig(path string) (*config.ServerConfig, error) {
viper.AddConfigPath(path)
viper.SetConfigName("app")
viper.SetConfigType("env")
viper.AutomaticEnv()
var config config.ServerConfig
err := viper.ReadInConfig()
if err != nil {
return nil, err
}
err = viper.Unmarshal(&config)
if err != nil {
return nil, err
}
return &config, nil
}
type Server struct {
server *http.Server
data *data.Data
cfg *config.ServerConfig
}
func NewServer(port uint) *Server {
func NewServer() *Server {
serverCfg, err := loadConfig(".")
if err != nil {
log.Fatal(err)
}
log.Println(serverCfg)
return &Server{
server: &http.Server{Addr: fmt.Sprintf(":%d", port)},
server: &http.Server{Addr: fmt.Sprintf(":%d", serverCfg.ServerPort)},
data: data.NewData(),
cfg: serverCfg,
}
}
func (s *Server) Run() error {
s.server.Handler = createHandler()
s.createHandler()
log.Printf("Server running on %s", s.server.Addr)
return s.server.ListenAndServe()
}
func createHandler() http.Handler {
func (s *Server) createHandler() {
r := chi.NewRouter()
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"http://localhost:4200"},
AllowedOrigins: strings.Split(s.cfg.AllowedOrigins, ","),
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
@ -51,7 +86,7 @@ func createHandler() http.Handler {
// Auth Router
r.Group(func(r chi.Router) {
ar := routers.NewAuthRouter()
ar := routers.NewAuthRouter(s.cfg)
ar.Route(r)
})
@ -138,7 +173,7 @@ func createHandler() http.Handler {
json.NewEncoder(w).Encode(map[string]string{"message": fmt.Sprintf("path %s are not exits", r.RequestURI)})
})
return r
s.server.Handler = r
}
func (s *Server) Shutdown(ctx context.Context) error {