Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
main: add server, connect redis middleware and static files
main.go | 91 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/main.go b/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c40f505f0dc3e282d1ae157a0bdee0870ae86fcf --- /dev/null +++ b/main.go @@ -0,0 +1,91 @@ +package main + +import ( + "fmt" + "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/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 main() { + if len(os.Args) < 2 { + fmt.Printf("Usage: %s server\n", os.Args[0]) + os.Exit(1) + } + + router := chi.NewRouter() + + // XXX: Fetch from configuration + ropts, err := goRedis.ParseURL("redis://") + if err != nil { + log.Fatal("Invalid redis host") + } + + rc := goRedis.NewClient(ropts) + 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) +}