Taobin-Recipe-Manager/server/server.go
Kenta420-Poom 8a6dc19bdd init Project ✌️✌️
2023-09-14 14:52:04 +07:00

51 lines
1,004 B
Go

package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"recipe-manager/data"
"recipe-manager/routers"
"github.com/go-chi/chi/v5"
)
type Server struct {
server *http.Server
data *data.Data
}
func NewServer(port uint) *Server {
return &Server{
server: &http.Server{Addr: fmt.Sprintf(":%d", port)},
data: data.NewData(),
}
}
func (s *Server) Run() error {
s.server.Handler = createHandler()
log.Printf("Server running on %s", s.server.Addr)
return s.server.ListenAndServe()
}
func createHandler() http.Handler {
r := chi.NewRouter()
rr := routers.NewRecipeRouter(data.NewData())
rr.Route(r)
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(map[string]string{"message": fmt.Sprintf("path %s are not exits", r.RequestURI)})
})
return r
}
func (s *Server) Shutdown(ctx context.Context) error {
return s.server.Shutdown(ctx)
}