如何在gin中使用路由器来服务HTML文件?



我正在练习使用gin框架来制作web服务器,并试图将'index.html'文件提供给web浏览器。所以,我搜索了如何管理它并编写如下代码,但它发生"http错误500"。哪些地方需要修改代码?

main.go

package main
import (
"comento/works/pkg/router"

)

func main(){
r := router.Router()    
r.Run(":8081")  

}
}

router.go

package router
import (
// "comento/works/pkg/api"
"github.com/gin-gonic/gin"
"net/http"

)
func Router() *gin.Engine {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.Header("Content-Type", "text/html")
c.HTML(http.StatusOK, "index.html", gin.H{})
})
return r
}

下面的目录状态工作.├──go.mod├──go.sum├──图片├──指数│├──index.html├──内部││├──globe .go├──main.go└──包裹├──api│├──image.go└──路由器└──router.go

您的代码出现以下错误:

运行时错误:无效内存地址或空指针解引用

你必须告诉Gin先加载HTML文件:

  • func (*gin.Engine).LoadHTMLFiles(files ...string)
  • func (*gin.Engine).LoadHTMLGlob(pattern string)

对于您提供的目录结构:

func Router() *gin.Engine {
r := gin.Default()
r.LoadHTMLFiles("index/index.html") // either individual files like this
// r.LoadHTMLGlob("index/*")        // or a glob pattern
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{})
})
return r
}

根据文档服务静态文件如下:

r.StaticFS("/index.html", http.Dir("<your_directory_name>"))

文件参考

最新更新