Gin
创建项目
mkdir ginupload && cd ginupload
go mod init ginupload
go get -u github.com/gin-gonic/gin
touch main.go
ginuploadgo mod
go getginmain.go
单文件上传
func main() {
    router := gin.Default()
    router.POST("/upload", func(c *gin.Context) {
        file, _ := c.FormFile("file")
        log.Println(file.Filename)

        c.SaveUploadedFile(file, "./" + file.Filename)

        c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
    })
    router.Run(":8080")
}
Gincurl
curl -X POST http://localhost:8080/upload \
  -F "file=@/tmp/upload.go" \
  -H "Content-Type: multipart/form-data"
upload.go
多文件上传
Gin
func main() {
    router := gin.Default()
    router.POST("/upload", func(c *gin.Context) {
        form, _ := c.MultipartForm()
        files := form.File["files"]

        for _, file := range files {
            log.Println(file.Filename)

            c.SaveUploadedFile(file, "./" + file.Filename)
        }
        c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
    })
    router.Run(":8080")
}

多文件的上传和单文件的区别不大,简单的几行代码就实现了文件上传的功能。

curl
curl -X POST http://localhost:8080/upload \
  -F "files=@/tmp/test1.zip" \
  -F "files=@/tmp/test2.zip" \
  -H "Content-Type: multipart/form-data"
test1.ziptest2.zip
限制文件大小
Gin
router := gin.Default()
router.MaxMultipartMemory = 8 << 20
MaxMultipartMemory
文件下载服务
goGin
func main() {
    router := gin.Default()

    router.GET("/local/file", func(c *gin.Context) {
        c.File("local/file.go")
    })
}
Gin
总结
GinGin
参考
  • gin-gonic/gin: Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance – up to 40 times faster. If you need smashing performance, get yourself some Gin.[3]

参考资料

[1]

gin-gonic/gin: Gin is a HTTP web framework written in Go (Golang).: https://github.com/gin-gonic/gin