// Package command is a small module for setting up an small development server. package command import ( "os" "github.com/pelletier/go-toml/v2" "github.com/rs/zerolog/log" "go.sebtobie.de/httpserver" "go.sebtobie.de/httpserver/middleware" "go.sebtobie.de/httpserver/middleware/db" ) // Site is an simple type for wrapping sites and their config paths in the absence of an **kwargs equivalent. type Site struct { // Config is the name of the mapitem with the config Config string // Site is the site itself Site httpserver.Site } // Server returns a initialized and configured Server. // custom authentication handlers are not configurable, since the server is preped for startup // Returns nil on errors and creates the config if the file does not exist, in the later case server and error are nil // The only middleware that is set up is: // - db.Middleware // - middleware.LogMiddleware func Server(config string, sites ...Site) (s *httpserver.Server, err error) { s = httpserver.CreateServer() s.Use(middleware.LogMiddleware) s.RegisterMiddleware("database", db.NewMiddleware()) for _, site := range sites { s.RegisterSite(site.Config, site.Site) } var conf *os.File if conf, err = os.Open(config); err != nil { log.Error().Err(err).Msg("Failed to open the file") if os.IsNotExist(err) { log.Info().Msg("Creating default config") conf, err = os.Create(config) if err != nil { log.Error().Err(err).Msg("Failed to create the default config") return nil, err } defer conf.Close() dec := toml.NewEncoder(conf) dec.Encode(s.Conf) return nil, nil } return nil, err } defer conf.Close() dec := toml.NewDecoder(conf) dec.Decode(s.Conf) s.Setup() return }