将Tus可恢复文件上传协议与Gin-Gonic CORS集成 [英] Integrating Tus Resumable File Upload Protocol with Gin-Gonic CORS issue

查看:140
本文介绍了将Tus可恢复文件上传协议与Gin-Gonic CORS集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了与Gin和Tus的CORS问题相关的类似问题;没有一个解决我目前遇到的问题.

I have looked at the similar questions here related to CORS issues with Gin and Tus; none addresses the problem I am currently having.

当前实现通过添加一个小的包装程序与标准net/http包一起使用.


// The wrapping function
func enableCors(w *http.ResponseWriter) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
}


// Simplified version of the code
composer := tusd.NewStoreComposer()
    store.UseIn(composer)

    handler, err := tusd.NewHandler(tusd.Config{
        BasePath:              "/files/",
        StoreComposer:         composer,
        NotifyCompleteUploads: true,
    })

    if err != nil {
        panic(fmt.Errorf("Unable to create handler %s", err))
    }

    go func() {
        for {
            fmt.Println("Waiting for upload to complete")
            event := <-handler.CompleteUploads
            fmt.Printf("Uploads %s finished\n", event.Upload.Storage)
        }
    }()

    http.Handle("/files/", func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            enableCors(&w)
            next.ServeHTTP(w, r)
        })
    }(http.StripPrefix("/files/", handler)))


    err = http.ListenAndServe(":8080", nil)
    if err != nil {
        panic(fmt.Errorf("unable to listen: %s", err))
    }
    

这是我对杜松子酒的尝试.我将处理程序包装在gin.WrapH()中.我添加了默认的Gin CORS库中间件,但cors错误仍然消失.这不起作用

Here is what I have tried with Gin. I wrapped the handler in gin.WrapH(). I added the default Gin CORS library middleware, and still, the cors error refused to go away. This is not working

func TusHandler() http.Handler {

    store := filestore.FileStore{
        Path: "./uploads",
    }

    composer := tusd.NewStoreComposer()
    store.UseIn(composer)

    handler, err := tusd.NewHandler(tusd.Config{
        BasePath:              "/upload/tus/",
        StoreComposer:         composer,
        NotifyCompleteUploads: true,
    })

    if err != nil {
        panic(err) // This is to simplify the code
    }

    return handler

}

// The routing
import "github.com/gin-contrib/cors"

router :=  gin.Default()
router.Use(cors.Default())
router.GET("/upload/tuts", gin.WrapH(uploader.TusHandler()))

这是我的浏览器输出.当我尝试上传指向Gin版本的文件

Here is my browser output. When I tried to upload a file pointing to the Gin version

杜松子酒的积分一直显示CORS错误.那就是我要解决的问题.

The gin integration keep showing CORS error. That is the problem I am trying to solve.

推荐答案

tus.io正在向服务器发送一堆头文件,因此您需要将这些头文件添加到cors配置中.错误消息是不允许使用名为 tus-resumable 的标头,您需要将此标头与tus.io发送的其他标头一起添加.并公开一些标头,以便tus-js-client可以读取它.

tus.io is sending a bunch of headers to the server so you need to add these headers to your cors config. The error message is saying that a header called tus-resumable is not allowed, you need to add this header along with other headers tus.io is sending. And expose some headers so tus-js-client can read it.

router.Use(cors.New(cors.Config{
        AllowAllOrigins: true,
        // AllowOrigins:  []string{"http://example.com"},
        AllowMethods:  []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
        AllowHeaders:  []string{"Authorization", "X-Requested-With", "X-Request-ID", "X-HTTP-Method-Override", "Upload-Length", "Upload-Offset", "Tus-Resumable", "Upload-Metadata", "Upload-Defer-Length", "Upload-Concat", "User-Agent", "Referrer", "Origin", "Content-Type", "Content-Length"},
        ExposeHeaders: []string{"Upload-Offset", "Location", "Upload-Length", "Tus-Version", "Tus-Resumable", "Tus-Max-Size", "Tus-Extension", "Upload-Metadata", "Upload-Defer-Length", "Upload-Concat", "Location", "Upload-Offset", "Upload-Length"},
    }))

如果您已经有一个正在运行的应用程序,则可以使用NewUnroutedHandler代替NewHandler.

Also if you already have a running app, you can use NewUnroutedHandler instead of NewHandler.

handler := dTusHandler()
router.POST("/files/", gin.WrapF(handler.PostFile))
router.HEAD("/files/:id", gin.WrapF(handler.HeadFile))
router.PATCH("/files/:id", gin.WrapF(handler.PatchFile))
router.GET("/files/:id", gin.WrapF(handler.GetFile))

这里是dTusHandler函数:

Here's dTusHandler func:

func dTusHandler() *tusd.UnroutedHandler {
    store := filestore.FileStore{
        Path: "./uploads",
    }

    composer := tusd.NewStoreComposer()
    store.UseIn(composer)

    h, err := tusd.NewUnroutedHandler(tusd.Config{
        BasePath:              "/files/",
        StoreComposer:         composer,
        NotifyCompleteUploads: true,
    })

    if err != nil {
        panic(fmt.Errorf("Unable to create handler: %s", err))
    }

    go func() {
        for {
            event := <-h.CompleteUploads
            fmt.Printf("Upload %s finished\n", event.Upload.ID)
        }
    }()

    return h

}

这篇关于将Tus可恢复文件上传协议与Gin-Gonic CORS集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆