gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:15:45 31 4
gpt4 key购买 nike

我正在使用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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com