I have looked at the similar questions here related to CORS issues with Gin and Tus; none addresses the problem I am currently having.
The current implementation works with the standard net/http package by adding a small wrapper.
// 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))
}
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()))
Here is my browser output. When I tried to upload a file pointing to the Gin version
The gin integration keep showing CORS error. That is the problem I am trying to solve.
In asp net 6 I fixed this with: