twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

Go 打包嵌入静态资源和模板 #407

Open twn39 opened 2 years ago

twn39 commented 2 years ago
package main

import (
    "embed"
    _ "embed"
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)

//go:embed web/build/*
var staticFs embed.FS

//go:embed views/*
var viewsFs embed.FS

func main() {
    views := template.Must(template.ParseFS(viewsFs, "views/*.html"))
    r := gin.Default()
    r.SetHTMLTemplate(views) // Since SetHTMLTemplate() is NOT thread-safe. It should only be called at initialization

    r.StaticFS("/static", http.FS(staticFs))
    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "title": "Gin web.",
        })
    })
    err := r.Run()
    if err != nil {
        panic(err.Error())
    } // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

main.go 需要在项目目录下,不然 views 目录会找不到。