package main import ( "bytes" "embed" "io/ioutil" "log" "net/http" "os" "path" "strings" "github.com/gin-gonic/gin" ) //go:embed static var assets embed.FS var BaseURL = "/" var indexTmpl []byte func getIndexHtml(c *gin.Context) { if len(indexTmpl) == 0 { if file, err := os.Open(path.Join(StaticDir, "index.html")); err != nil { log.Println("Unable to open index.html: ", err) } else { defer file.Close() if indexTmpl, err = ioutil.ReadAll(file); err != nil { log.Println("Cannot read whole index.html: ", err) } else { indexTmpl = bytes.Replace(indexTmpl, []byte("{{.urlbase}}"), []byte(path.Clean(path.Join(BaseURL+"/", "nuke"))[:len(path.Clean(path.Join(BaseURL+"/", "nuke")))-4]), -1) } } } c.Writer.Write(indexTmpl) } var staticFS http.FileSystem func serveFile(c *gin.Context, url string) { c.Request.URL.Path = url http.FileServer(staticFS).ServeHTTP(c.Writer, c.Request) } func declareStaticRoutes(router *gin.RouterGroup, baseURL string) { router.GET("/", func(c *gin.Context) { getIndexHtml(c) }) router.GET("/exercices/*_", func(c *gin.Context) { getIndexHtml(c) }) router.GET("/themes/*_", func(c *gin.Context) { getIndexHtml(c) }) router.GET("/css/*_", func(c *gin.Context) { serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL)) }) router.GET("/fonts/*_", func(c *gin.Context) { serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL)) }) router.GET("/img/*_", func(c *gin.Context) { serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL)) }) router.GET("/js/*_", func(c *gin.Context) { serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL)) }) router.GET("/views/*_", func(c *gin.Context) { serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL)) }) }