server/qa/static.go

76 lines
1.7 KiB
Go
Raw Normal View History

package main
import (
"bytes"
2022-11-06 15:36:31 +00:00
"embed"
"io/ioutil"
"log"
"net/http"
"os"
"path"
2022-11-06 15:36:31 +00:00
"strings"
2022-11-06 15:36:31 +00:00
"github.com/gin-gonic/gin"
)
2022-11-06 15:36:31 +00:00
//go:embed static
var assets embed.FS
var BaseURL = "/"
var indexTmpl []byte
2022-11-06 15:36:31 +00:00
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)
}
}
}
2022-11-06 15:36:31 +00:00
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)
}
2022-11-06 15:36:31 +00:00
func declareStaticRoutes(router *gin.RouterGroup, baseURL string) {
router.GET("/", func(c *gin.Context) {
getIndexHtml(c)
})
2022-11-06 15:36:31 +00:00
router.GET("/exercices/*_", func(c *gin.Context) {
getIndexHtml(c)
})
2022-11-06 15:36:31 +00:00
router.GET("/themes/*_", func(c *gin.Context) {
getIndexHtml(c)
})
2022-11-06 15:36:31 +00:00
router.GET("/css/*_", func(c *gin.Context) {
serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
})
2022-11-06 15:36:31 +00:00
router.GET("/fonts/*_", func(c *gin.Context) {
serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
})
2022-11-06 15:36:31 +00:00
router.GET("/img/*_", func(c *gin.Context) {
serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
})
2022-11-06 15:36:31 +00:00
router.GET("/js/*_", func(c *gin.Context) {
serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
})
2022-11-06 15:36:31 +00:00
router.GET("/views/*_", func(c *gin.Context) {
serveFile(c, strings.TrimPrefix(c.Request.URL.Path, baseURL))
})
}