静态文件服务
func main() {
router := gin.Default()
//设置静态文件目录,如果访问localhost:8080/assets/test.txt
//如果./assets/test.txt文件存在,那么就返回该文件,否则返回404
router.Static("/assets", "./assets")
//和上面的功能一样
router.StaticFS("/my_file", gin.Dir("my_file",true))
//为单个文件绑定路由
//可以通过访问localhost:8080/family.pic来获取./pic/family.pic文件
router.StaticFile("/family.pic", "./pic/family.pic")
router.Run()
}
从 reader 提供数据
func main() {
router := gin.Default()
router.GET("/someDataFromReader", func(c *gin.Context) {
response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
if err != nil || response.StatusCode != http.StatusOK {
c.Status(http.StatusServiceUnavailable)
return
}
reader := response.Body
contentLength := response.ContentLength
contentType := response.Header.Get("Content-Type")
extraHeaders := map[string]string{
"Content-Disposition": `attachment; filename="gopher.png"`,
}
c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
})
router.Run(":8080")
}
HTML 渲染
使用 LoadHTMLGlob () 或 LoadHTMLFiles ()
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
})
})
router.Run(":8080")
}
templates/index.tmpl
<html>
<h1>
{{ .title }} //使用.来取变量
</h1>
</html>
与embed结合
package main
import (
"embed"
"net/http"
"github.com/gin-gonic/gin"
)
//go:embed static
var static embed.FS
func main() {
router := gin.Default()
router.StaticFS("/", http.FS(static))
//router.StaticFS("/", gin.Dir("static", true))
router.Run(":8080")
}