babillard/cmd/server.go

73 lines
1.8 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"fmt"
"log"
"net/http"
"codeberg.org/vlbeaudoin/serpents"
"git.agecem.com/agecem/babillard/handlers"
"git.agecem.com/agecem/babillard/public"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// serverCmd represents the server command
var serverCmd = &cobra.Command{
Use: "server",
Short: "Démarrer le serveur web",
Run: func(cmd *cobra.Command, args []string) {
port := viper.GetInt("server.port")
//static_dir := viper.GetString("server.static_dir")
runServer(port)
},
}
func init() {
rootCmd.AddCommand(serverCmd)
declareFlags(serverCmd.Flags())
}
func declareFlags(flagSet *pflag.FlagSet) {
if err := serpents.IntP(flagSet, "server.port", "port", "p", 8080, "Port réseau à utiliser pour le serveur"); err != nil {
log.Fatal(err)
}
if err := serpents.String(flagSet, "server.contenu_dir", "contenu_dir", "contenu", "Répertoire du contenu à exposer"); err != nil {
log.Fatal(err)
}
}
func runServer(port int) {
log.Print("[I] Starting webserver")
e := echo.New()
e.Pre(middleware.AddTrailingSlash())
e.Group("").Use(middleware.StaticWithConfig(middleware.StaticConfig{
Root: "/html/",
Filesystem: http.FS(public.HTMLFS()),
}))
e.Group("/public/css").Use(middleware.StaticWithConfig(middleware.StaticConfig{
Root: "/css/",
Filesystem: http.FS(public.CSSFS()),
}))
e.Group("/public/js").Use(middleware.StaticWithConfig(middleware.StaticConfig{
Root: "/js/",
Filesystem: http.FS(public.JSFS()),
}))
groupAPI := e.Group("/api")
groupAPI.GET("/", handlers.HandleAPIShow)
groupAPI.GET("/contenu/", handlers.HandleAPIContenuList)
groupAPI.GET("/contenu/:filename/", handlers.HandleAPIContenuFile)
e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", port)))
}