I'm very grateful that I usually use gin to create web services.
However, I felt that LoadHTMLGlob is a slightly bad implementation. When loading a nested HTML file with LoadHTMLGlob, you must define it in the tmpl file.
If you implement the following implementation, how do you think HTML can be called immediately?
gin
package gin
import (
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
)
var filepathArray []string
func LoadHTMLGlob(path string) {
var rootDir string
if strings.HasSuffix(path, "*") {
rootDir = strings.Split(path, "/")[0]
}
err := filepath.Walk(rootDir, func(p string, info os.FileInfo, err error) error {
if strings.HasSuffix(p, ".html") {
filepathArray = append(filepathArray, p)
}
return nil
})
if err != nil {
panic(err)
}
}
func GET(endpoint, file string) {
var path string
for _, p := range filepathArray {
if strings.HasSuffix(p, file) {
path = p
}
}
fmt.Println(endpoint + "->" + path)
http.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles(path)
if err != nil {
panic(err)
}
err = tmpl.Execute(w, nil)
if err != nil {
panic(err)
}
})
}
func Run(port string) {
http.ListenAndServe(port, nil)
}
User write main.go
package main
import (
"github.com/konojunya/html-glob-handler/gin"
)
func main() {
gin.LoadHTMLGlob("views/*")
gin.GET("/", "home/index.html")
gin.Run(":8000")
}
What I'd like to say is not to make gin.Run possible, but I also want LoadHTMLGlob to be able to read HTML files in deep Directory.
Thanks.
Comment From: thinkerou
https://github.com/gin-gonic/gin/blob/master/gin_test.go#L62 can not?
Comment From: konojunya
@thinkerou
I think that it is impossible to load nested HTML without using define.
I hope to solve this problem somewhat. Just for myself and the world front end, we often deal with React and Vue etc, and I think that the priority is not so high as there are few use cases for loading nested views with LoadHTMLGlob.
but, I want to read nested ones in .html.
Comment From: thinkerou
OK please see https://github.com/gin-gonic/gin/pull/1296
Comment From: konojunya
@thinkerou thanks! :)