How to render static files within Gin router?
Asked Answered
B

2

15

I want to serve a JSON file with gin server. And set some customize values in the HTML file. Use JavaScript in it to call the JSON file.

My application structure:

.
├── main.go
└── templates
    ├── index.html
    └── web.json

I put these basic source into main.go file:

package main

import (
    "net/http"

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

var router *gin.Engine

func main() {
    router = gin.Default()
    router.LoadHTMLGlob("templates/*")

    router.GET("/web", func(c *gin.Context) {
        c.HTML(
            http.StatusOK,
            "index.html",
            gin.H{
                "title": "Web",
                "url":   "./web.json",
            },
        )
    })

    router.Run()
}

Some code in templates/index.html file:

<!doctype html>
<html>

  <head>
    <title>{{ .title }}</title>

    // ...
  </head>

  <body>
    <div id="swagger-ui"></div>

    // ...
    
    <script>
      window.onload = function() {
        // Begin Swagger UI call region
        const ui = SwaggerUIBundle({
          url: "{{ .url }}",
          dom_id: '#swagger-ui',
          // ...
        })
        // End Swagger UI call region

        window.ui = ui
      }
    </script>

  </body>
</html>

When running the application, I got a fetch error:

Not Found ./web.json

So how should I serve the web.json file to be accessed in the Gin internal server?

Bueno answered 5/8, 2019 at 7:55 Comment(0)
B
24

Quoting the gin docs for serving static files:

func main() {
    router := gin.Default()
    router.Static("/assets", "./assets")
    router.StaticFS("/more_static", http.Dir("my_file_system"))
    router.StaticFile("/favicon.ico", "./resources/favicon.ico")
    router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))

    // Listen and serve on 0.0.0.0:8080
    router.Run(":8080")
}

So basically you should define a route specific to your JSON file next to other routes you've defined. And then use that.

Blaine answered 5/8, 2019 at 7:59 Comment(3)
It's the simple way. But how can I set dynamic url param here?Bueno
@Bueno yes that's how you do it, perhaps have a GET param, and do the file grabbing manuallyBlaine
The last method reouter.StaticFileFS`` ends up doing a redirect for me when using embed.FS```. Also, wrong linkSend
U
2

if you want to serve static file according by the query path, you can do like this:

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

    r.GET("/*path", func(c *gin.Context) {
        // read from file
        data, err := os.ReadFile("/path/to/file")
        if err != nil {
            // error handler
        }
        switch path.Ext(c.Request.URL.Path) {
        case ".html":
            c.Header("Content-Type", "text/html")
        case ".css":
            c.Header("Content-Type", "text/css")
        case ".js":
            c.Header("Content-Type", "application/javascript")
            // ...
        }
        _, _ = c.Writer.Write(data)
    })
    // Listen and serve on 0.0.0.0:8080
    panic(r.Run(":8080"))
}
Unwept answered 1/3, 2023 at 2:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.