Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
cmd/server: move into a separated command
cmd/server.go | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/cmd/server.go b/cmd/server.go new file mode 100644 index 0000000000000000000000000000000000000000..379653d1d022a7fb5c07c37bdf283f1909b3eb6c --- /dev/null +++ b/cmd/server.go @@ -0,0 +1,94 @@ +package cmd + +import ( + "os" + "log" + "path/filepath" + "strings" + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + goRedis "github.com/go-redis/redis/v8" + + "git.eletrotupi.com/git/dinheiro/config" + "git.eletrotupi.com/git/dinheiro/redis" +) + +func FileServer(router chi.Router, path string, root http.FileSystem) { + if strings.ContainsAny(path, "{}*") { + // TODO: Should we abort here? + log.Fatal("FileServer does not permit any URL parameters.") + os.Exit(1) + } + + if path != "/" && path[len(path)-1] != '/' { + router.Get(path, http.RedirectHandler(path + "/", 301).ServeHTTP) + path += "/" + } + + path += "*" + + router.Get(path, func(w http.ResponseWriter, r *http.Request) { + rctx := chi.RouteContext(r.Context()) + pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*") + fs := http.StripPrefix(pathPrefix, http.FileServer(root)) + fs.ServeHTTP(w, r) + }) +} + +func registerStaticRoutes(router chi.Router) { + // TODO: Deal with cache busting + workDir, _ := os.Getwd() + publicDir := http.Dir(filepath.Join(workDir, "public")) + + FileServer(router, "/public", publicDir) +} + +func registerRoutes(router chi.Router) { + registerStaticRoutes(router) + + router.Get("/", func(w http.ResponseWriter, r *http.Request) { + fileData, err := os.ReadFile("./templates/index.html") + + if err != nil { + log.Fatal("Couldn't open file") + os.Exit(1) + } + + w.Write(fileData) + }) +} + +func Server() { + appConfig := config.LoadConfig() + + router := chi.NewRouter() + + // XXX: We should probably have a struct holding all this together + redisHost, ok := appConfig.Get("redis", "redis-host") + if !ok { + log.Fatalf("Invalid redis::redis-host config") + } + + ropts, err := goRedis.ParseURL(redisHost) + if err != nil { + log.Fatal("Invalid redis host") + } + + rc := goRedis.NewClient(ropts) + router.Use(config.Middleware(appConfig)) + router.Use(redis.Middleware(rc)) + router.Use(middleware.RealIP) + router.Use(middleware.Logger) + + registerRoutes(router) + + addr := ":8555" + if len(os.Args) > 2 { + addr = os.Args[2] + } + + log.Printf("Listening on %s", addr) + http.ListenAndServe(addr, router) +}