Description

I am trying to serve a React app, and it's mostly working, except that parameter pages aren't loading properly.

I'm doing the following and running into an issue where visiting /route1/foo returns a 404, but visiting /route1 or /route2 works well. I came across this approach using NoRoute - https://github.com/gin-gonic/gin/issues/2920#issuecomment-977993091 - but it's not clear to me if that's really the best way forward.

I want React to take care of routing. To do that, I just need to have the static asset dir returned for every route that's not from a small list, e.g. the /api/graphql calls below. What's the best way to do that?

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-contrib/static"
)

func main() {
    serviceName := os.Getenv("TRACER_SERVICE_NAME")

    r := gin.Default()
    r.SetTrustedProxies(nil)

    staticAssetsDir := os.Getenv("STATIC_ASSETS_DIR")
         fs := static.LocalFile(staticAssetsDir, false)
     r.Use(static.Serve("/", fs)
     r.Use(static.Serve("/route1", fs)
     r.Use(static.Serve("/route2", fs)
     r.Use(static.Serve("/route1/:param", fs)

    // h := a.HTTPHandler()
    r.POST("/api/graphql", gin.WrapH(http.NewBoundResolver().HTTPHandler()))
    r.GET("/api/graphql", gin.WrapH(ui.NewGraphQLUIHandlerFunc()))

    r.Run("0.0.0.0:" + portStr) // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Comment From: UniKylin

I think you confused React's route with Gin's route

Comment From: cinjon

I'm not sure what you mean by "confused". When a user hits the webpage for the first time or opens a new tab, they are going to get Gin's route handing. When they are navigating on the web page, they are going to get React's route handling. I would like for Gin to just return the static assets in all cases so that React can take over (except when we're trying to hit the graphql api).

Comment From: pscheid92

AFAIK, this is a limitation of http.StripPrefix, used with http.FileServer as a foundation for static file serving. It cannot handle wildcards because net/http itself doesn't provide this capability.

The "catch everything and serve static files approach from there" with router.NoRouteyou shared seems the best way to go to me.

I found another issue giving more examples; maybe this is helpful for you, too. 👉 https://github.com/gin-gonic/contrib/issues/90#issuecomment-990237367

Comment From: cinjon

Thanks for replying. The NoRoute approach worked and the solution you sent is even better. I appreciate it @pscheid92 .