猿问

如何在 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>

运行应用程序时,我收到获取错误:


未找到./web.json


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


慕姐4208626
浏览 143回答 2
2回答

慕村9548890

引用原始杜松子酒文档:https://github.com/gin-gonic/gin#serving-static-filesfunc main() {&nbsp; &nbsp; router := gin.Default()&nbsp; &nbsp; router.Static("/assets", "./assets")&nbsp; &nbsp; router.StaticFS("/more_static", http.Dir("my_file_system"))&nbsp; &nbsp; router.StaticFile("/favicon.ico", "./resources/favicon.ico")&nbsp; &nbsp; // Listen and serve on 0.0.0.0:8080&nbsp; &nbsp; router.Run(":8080")}因此基本上您应该在您定义的其他路由旁边定义一个特定于 JSON 文件的路由。然后使用它。

慕婉清6462132

如果你想根据查询路径提供静态文件,你可以这样做:func serve() {&nbsp; &nbsp; r := gin.Default()&nbsp; &nbsp; r.GET("/*path", func(c *gin.Context) {&nbsp; &nbsp; &nbsp; &nbsp; // read from file&nbsp; &nbsp; &nbsp; &nbsp; data, err := os.ReadFile("/path/to/file")&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // error handler&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; switch path.Ext(c.Request.URL.Path) {&nbsp; &nbsp; &nbsp; &nbsp; case ".html":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Content-Type", "text/html")&nbsp; &nbsp; &nbsp; &nbsp; case ".css":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Content-Type", "text/css")&nbsp; &nbsp; &nbsp; &nbsp; case ".js":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.Header("Content-Type", "application/javascript")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; _, _ = c.Writer.Write(data)&nbsp; &nbsp; })&nbsp; &nbsp; // Listen and serve on 0.0.0.0:8080&nbsp; &nbsp; panic(r.Run(":8080"))}
随时随地看视频慕课网APP

相关分类

Go
我要回答