json - 如何在 Gin 路由器中呈现静态文件?

标签 json go server static go-gin

我想用 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>

运行应用程序时,出现获取错误:

Not Found ./web.json

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

最佳答案

引用原始 gin 文档: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 文件的路由。然后使用它。

关于json - 如何在 Gin 路由器中呈现静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57354389/

相关文章:

android - 导入 JSON 文件而不覆盖 Firebase 中的现有数据

javascript - 动态定义 Ember 数据模型的属性

go - 转到httprouter自定义中间件

json - 如何使用 json.NewDecoder 在 Go 中处理 json 响应中的空值

安卓。 OKHttp。如何从正文 POST 响应中找到时间服务器?

ios - 在 Swift 2 中过滤任何对象

c# - XmlNodeConverter 只能转换以对象开头的JSON

go - 在另一个文件夹中导入本地包

r - 包的安装具有非零退出状态 - Linux 服务器

php - 在服务器上为多个用户运行 MySql