go - Gin 上传文件时始终返回204

标签 go go-gin

我正在使用OPTIONS方法获得204,但是似乎没有碰到终点
enter image description here

只需构建一个简单的文件上传端点,如下所示:

package main

import  (
    "cloud.google.com/go/storage"
    "github.com/gin-gonic/gin"
    "github.com/gin-contrib/cors"
    "google.golang.org/api/option"
    "io"
    "log"
)

 const uploadBucket = "some-cool-bucket-name"
 const uploadApiKey = "some-advanced-key"

func main() {
    router := gin.Default()

    rg := router.Group("api/v1/photo")
    {
        rg.PATCH("/", uploadFile)
    }

    router.Use(cors.Default())

    router.Run()
}

func uploadFile(c *gin.Context) {
    mr, e := c.Request.MultipartReader()
    if e != nil {
        panic("Error reading request")
    }

    client, e := storage.NewClient(c, option.WithAPIKey(uploadApiKey))
    bucket := client.Bucket(uploadBucket)

    for {
        p, e := mr.NextPart()

        if e == io.EOF {
            break
        } else if e != nil {
            panic("Error processing file")
        }

        w := bucket.Object(p.FileName()).NewWriter(c)

        if _, e := io.Copy(w, p); e != nil {
            panic("Error during chunk upload")
        } else if e := w.Close(); e != nil {
            panic("Could not finalize chunk writing")
        }

    }
}

有什么想法吗?

最佳答案

在CORS下使用:

func CORS() gin.HandlerFunc {
    // TO allow CORS
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }
        c.Next()
    }
}

接下来,您必须在路线上添加cors:
    router := gin.Default()
    router.Use(CORS())

另外,最好使用POST方法代替PATCH。我很确定它将解决您的问题。

关于go - Gin 上传文件时始终返回204,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60352263/

相关文章:

file - go) 我如何提供下载服务?

go - 当我重定向初始请求时如何在 Gin 中记录响应正文

reactjs - 如何通过react/axios和golang/gin上传图片到S3

去新手: Getting "mismatched types *int and int" error when trying to compare reference to static integer

docker - 带有 Cloud Foundry CLI 的 Golang Docker

html - Golang 模板将 html 解释为纯文本

go - 优雅地处理 gin-gonic 中的模板渲染错误

go - 如何在使用gin框架进行模拟时将json数据作为请求参数传递

go - 如何从 *http.Request 和 *httptest.ResponseRecorder 创建 gin.Context?

php - 在 PHP 中调用 Go RPC 套接字方法