静态文件服务

  1. func main() {
  2. router := gin.Default()
  3. //设置静态文件目录,如果访问localhost:8080/assets/test.txt
  4. //如果./assets/test.txt文件存在,那么就返回该文件,否则返回404
  5. router.Static("/assets", "./assets")
  6. //和上面的功能一样
  7. router.StaticFS("/my_file", gin.Dir("my_file",true))
  8. //为单个文件绑定路由
  9. //可以通过访问localhost:8080/family.pic来获取./pic/family.pic文件
  10. router.StaticFile("/family.pic", "./pic/family.pic")
  11. router.Run()
  12. }

从 reader 提供数据

  1. func main() {
  2. router := gin.Default()
  3. router.GET("/someDataFromReader", func(c *gin.Context) {
  4. response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
  5. if err != nil || response.StatusCode != http.StatusOK {
  6. c.Status(http.StatusServiceUnavailable)
  7. return
  8. }
  9. reader := response.Body
  10. contentLength := response.ContentLength
  11. contentType := response.Header.Get("Content-Type")
  12. extraHeaders := map[string]string{
  13. "Content-Disposition": `attachment; filename="gopher.png"`,
  14. }
  15. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  16. })
  17. router.Run(":8080")
  18. }

HTML 渲染

使用 LoadHTMLGlob () 或 LoadHTMLFiles ()

  1. func main() {
  2. router := gin.Default()
  3. router.LoadHTMLGlob("templates/*")
  4. //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  5. router.GET("/index", func(c *gin.Context) {
  6. c.HTML(http.StatusOK, "index.tmpl", gin.H{
  7. "title": "Main website",
  8. })
  9. })
  10. router.Run(":8080")
  11. }

templates/index.tmpl

  1. <html>
  2. <h1>
  3. {{ .title }} //使用.来取变量
  4. </h1>
  5. </html>

与embed结合

  1. package main
  2. import (
  3. "embed"
  4. "net/http"
  5. "github.com/gin-gonic/gin"
  6. )
  7. //go:embed static
  8. var static embed.FS
  9. func main() {
  10. router := gin.Default()
  11. router.StaticFS("/", http.FS(static))
  12. //router.StaticFS("/", gin.Dir("static", true))
  13. router.Run(":8080")
  14. }