Json 如何在Gin路由器中呈现静态文件?
我想用gin服务器提供一个JSON文件。并在HTML文件中设置一些自定义值。在其中使用JavaScript调用JSON文件 我的应用程序结构:Json 如何在Gin路由器中呈现静态文件?,json,go,server,static,go-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" )
.
├── 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()
}
<!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>
模板/index.html
文件中的一些代码:
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()
}
<!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>
{{.title}
// ...
// ...
window.onload=函数(){
//开始招摇过市UI调用区域
const ui=SwaggerUIBundle({
url:“{.url}}”,
dom_id:“#招摇过市用户界面”,
// ...
})
//结束招摇UI调用区域
window.ui=ui
}
运行应用程序时,我遇到一个获取错误:
找不到。/web.json
那么,我应该如何提供要在Gin内部服务器中访问的
web.json
文件?引用原始Gin文档:
因此,基本上,您应该在已定义的其他路由旁边定义特定于JSON文件的路由。然后使用它。这是最简单的方法。但是我如何在这里设置动态
url
param?@0200402是的,您就是这样做的,可能有一个GET param,并手动抓取文件