'How to serve static files from all routes except one in Gin? [duplicate]

As the title says, consider a Gin router where I want to serve static files from all routes except one. Let's say this one route is /api. A first attempt might look like this:

package main

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

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

    r.StaticFS("/", gin.Dir("static", false))
    r.GET("/api/v1/foo", func(c *gin.Context) { c.JSON(200, gin.H{"foo": true}) })

    r.Run(":9955")
}

The RouterGroup.StaticFS (and Static too) under the hood joins the relative path with a wildcard path param: path.Join(relativePath, "/*filepath"). When relativePath is the root path /, it will panic with:

panic: '/api/v1/foo' in new path '/api/v1/foo' conflicts with existing wildcard '/*filepath' in existing prefix '/*filepath'

This is due to Gin's http router implementation: routing matches on the path prefix, so a wildcard on root will conflict with every other route. More details about this behavior can be found here — which is where this question was raised.

Another possible solution is to prefix the static file route, so that it doesn't conflict with /api:

r.StaticFS("/static", gin.Dir("static", false))

but this doesn't allow me to serve assets from root too. How can I have a wildcard, or equivalent, on root and still match on one specific path?



Solution 1:[1]

It has to do with how the Purge CSS works.

Long and short of it is that, if you check the tailwind config file for the path to scan for tailwind classes and then scan for classes that appears as a substring and hence the dynamically generated ones fail in your case.

So when you run the first program and execute the server. tailwind goes like.. oh, user needs the class of w-0 so I am gonna keep it and add it to the final output file. But Purge CSS cannot execute JS and hence cannot compute dynamic strings which might be used as class names.

Check this answer too

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oreopot