【问题标题】:How to render static files within Gin router?如何在 Gin 路由器中渲染静态文件?
【发布时间】:2019-12-12 17:29:52
【问题描述】:

我想用 gin 服务器提供一个 JSON 文件。并在 HTML 文件中设置一些自定义值。使用其中的 JavaScript 调用 JSON 文件。

我的应用结构:

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

我将这些基本源码放入main.go文件中:

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()
}

templates/index.html 文件中的一些代码:

<!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>

在运行应用程序时,我收到了一个 fetch 错误:

未找到 ./web.json

那么我应该如何提供web.json 文件在Gin 内部服务器中访问?

【问题讨论】:

    标签: json go server static go-gin


    【解决方案1】:

    引用原始杜松子酒文档: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")
    }
    

    所以基本上你应该在你定义的其他路由旁边定义一个特定于你的 JSON 文件的路由。然后使用它。

    【讨论】:

    • 这是最简单的方法。但是如何在这里设置动态url 参数?
    • @02040402 是的,你就是这样做的,也许有一个 GET 参数,然后手动抓取文件
    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2016-02-24
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多