【发布时间】: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