golang gin的静态文件处理

2022年 1月 8日 120点热度 0人点赞

废话不多说,项目结构按照如下的目录来安排,应该是够用了。

 

main.go

代码如下:

package main

import (
   "fmt"
   "github.com/gin-gonic/gin"
   "net/http"
)

func main() {
   router := gin.Default()
   router.LoadHTMLFiles("./view/index.html", "./view/upload.html")
   // 加载静态资源,例如网页的css、js
   router.Static("/static", "./static")

   // 加载静态资源,一般是上传的资源,例如用户上传的图片
   router.StaticFS("/upload", http.Dir("upload"))

   // 加载单个静态文件
   router.StaticFile("/favicon.ico", "./static/favicon.ico")

   router.GET("/", func(context *gin.Context) {
      context.HTML(http.StatusOK, "index.html", nil)
   })

   // 如果不加这个是不能通过localhost:8080/index.html访问到index.html文件的
   router.GET("/index.html", func(context *gin.Context) {
      context.HTML(http.StatusOK, "index.html", nil)
   })

   router.POST("/upload", func(context *gin.Context) {
      file, _ := context.FormFile("file")
      // 上传文件至指定目录
      if err := context.SaveUploadedFile(file, "./upload/"+file.Filename); err != nil {
         fmt.Println(err)
      }
      context.HTML(http.StatusOK, "upload.html", gin.H{"file": "/upload/" + file.Filename})
   })

   router.Run(":8080")
}

 

index.html

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link rel="stylesheet" href="/static/css/index.css">
</head>

<body>
<h1>你好吗?</h1>
</body>
</html>

 

rainbow

这个人很懒,什么都没留下

文章评论