pink_fox/application/packages/fw/cmd_server.go

78 lines
1.9 KiB
Go

package fw
import (
"fmt"
"github.com/go-chi/chi/v5"
"github.com/spf13/cobra"
"net/http"
)
type ServerConfig[T, U any] struct {
InitStorage func(port int, pathConfig string) (storage T, err Error)
GetDebugMode func(T) bool
GetLogger func(T) Logger
InitServerEngine func(T) (*chi.Mux, Error)
RegistrationRoutes func(*RouterManager[T, U])
MakeContainer func(T, http.ResponseWriter, *http.Request) U
CloseContainer func(U)
}
func GetCmdServer[T, U any](config ServerConfig[T, U], portDefault int, configPathDefault string) Command {
port := portDefault
configPath := configPathDefault
return Command{
Use: "server",
Short: "start the server",
Run: func(cmd *cobra.Command, args []string) {
storage, err := config.InitStorage(port, configPath)
if err != nil {
Exit(err)
}
var engine *chi.Mux
if config.InitServerEngine != nil {
engine, err = config.InitServerEngine(storage)
if err != nil {
Exit(err)
}
} else {
engine = DefaultServerEngine()
}
debugMode := false
if config.GetDebugMode != nil {
debugMode = config.GetDebugMode(storage)
}
var logger Logger = nil
if config.GetLogger != nil {
logger = config.GetLogger(storage)
}
routesManager := NewRouterManager[T, U](
engine,
storage,
config.MakeContainer,
config.CloseContainer,
debugMode,
logger,
)
config.RegistrationRoutes(routesManager)
fmt.Printf("Starting http_server at port %d...", port)
err_ := http.ListenAndServe(":12001", engine)
if err_ != nil {
Exit(Err(fmt.Errorf("error starting http server: %v", err)))
}
},
Init: func(cmd *cobra.Command) {
cmd.Flags().IntVarP(&port, "port", "p", port, "start http server on port")
cmd.Flags().StringVarP(&configPath, "config", "c", configPath, "config file path")
},
}
}
func DefaultServerEngine() *chi.Mux {
return chi.NewRouter()
}