亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Gin 路由器中渲染靜態文件?

如何在 Gin 路由器中渲染靜態文件?

Go
慕姐4208626 2023-07-10 14:53:59
我想使用 gin 服務器提供 JSON 文件。并在 HTML 文件中設置一些自定義值。在其中使用 JavaScript 來調用 JSON 文件。我的應用程序結構:.├── main.go└── templates    ├── index.html    └── web.json我將這些基本源代碼放入main.go文件中:package mainimport (    "net/http"    "github.com/gin-gonic/gin")var router *gin.Enginefunc 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那么我應該如何web.json在Gin內部服務器中提供要訪問的文件呢?
查看完整描述

2 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

引用原始杜松子酒文檔: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 文件的路由。然后使用它。


查看完整回答
反對 回復 2023-07-10
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

如果你想根據查詢路徑提供靜態文件,你可以這樣做:


func serve() {

    r := gin.Default()


    r.GET("/*path", func(c *gin.Context) {

        // read from file

        data, err := os.ReadFile("/path/to/file")

        if err != nil {

            // error handler

        }

        switch path.Ext(c.Request.URL.Path) {

        case ".html":

            c.Header("Content-Type", "text/html")

        case ".css":

            c.Header("Content-Type", "text/css")

        case ".js":

            c.Header("Content-Type", "application/javascript")

            // ...

        }

        _, _ = c.Writer.Write(data)

    })

    // Listen and serve on 0.0.0.0:8080

    panic(r.Run(":8080"))

}


查看完整回答
反對 回復 2023-07-10
  • 2 回答
  • 0 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號