Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render static files within Gin router?

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?

like image 747
02040402 Avatar asked Aug 05 '19 07:08

02040402


Video Answer


1 Answers

Quoting the original gin docs: https://github.com/gin-gonic/gin#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")

    // 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.

like image 151
Seaskyways Avatar answered Sep 18 '22 22:09

Seaskyways