简体   繁体   English

如何在杜松子酒中使用路由器提供 html 文件?

[英]how to serve html file with using router in gin?

I'm practicing using gin framework to make web server and trying to serve 'index.html' file to web browser.我正在练习使用 gin 框架制作 web 服务器,并尝试将“index.html”文件提供给 web 浏览器。 so, I searched about how to manage it and wrote code like below but it occures 'http error 500 '.所以,我搜索了如何管理它并编写了如下代码,但它发生了“http error 500”。 Where I have to amend codes?我必须在哪里修改代码?

main.go主要.go

    package main

import (
    "comento/works/pkg/router"
    
)



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

}

router.go路由器.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
}

and directory status below和下面的目录状态

works.作品。 ├── go.mod ├── go.sum ├── images ├── index │ └── index.html ├── internal │ └── global.go ├── main.go └── pkg ├── api │ └── image.go └── router └── router.go ├── go.mod ├── go.sum ├── images ├── index │ └── index.html ├── internal │ └── global.go ├── main.go └── pkg ├─ ─ api │ └── image.go └── router └── router.go

You have to tell gin to load the HTML files first using either r.LoadHTMLGlob() or r.LoadHTMLFiles() .您必须先使用r.LoadHTMLGlob()r.LoadHTMLFiles()告诉 gin 加载 HTML 文件。

In your case with your directory structure:在您的目录结构的情况下:

func Router() *gin.Engine {
    r := gin.Default()
    r.LoadHTMLFiles("index/index.html") // either a single file 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
}

Accorfing to Documents serving static file is as followings:根据 Documents serving static 文件如下:

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

Documents reference文件参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM