[英]How to render static files within Gin router?
我想用 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>
運行應用程序時,我收到一個獲取錯誤:
未找到 ./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 文件的路由。 然后使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.