英文:
how to serve html file with using router in gin?
问题
我正在使用gin框架练习制作Web服务器,并尝试向Web浏览器提供'index.html'文件。所以,我搜索了如何管理它,并编写了下面的代码,但出现了'HTTP错误500'。我应该在哪里修改代码?
main.go
package main
import (
	"comento/works/pkg/router"
)
func main(){
	r := router.Router()	
	r.Run(":8081")	
}
router.go
package router
import (
	"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
}
目录结构如下:
works
.
├── go.mod
├── go.sum
├── images
├── index
│   └── index.html
├── internal
│   └── global.go
├── main.go
└── pkg
├── api
│   └── image.go
└── router
└── router.go
英文:
I'm practicing using gin framework to make web server and trying to serve 'index.html' file to web browser. so, I searched about how to manage it and wrote code like below but it occures 'http error 500 '. Where I have to amend codes?
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
}
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
答案1
得分: 1
以下是代码的翻译部分:
您的代码出现以下错误:
> 运行时错误:无效的内存地址或空指针解引用
您需要告诉 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") // 可以像这样加载单个文件
    // r.LoadHTMLGlob("index/*")        // 或者使用通配符模式
    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{})
    })
    return r
}
英文:
The following error occurs with your code:
> runtime error: invalid memory address or nil pointer dereference
You have to tell Gin to load the HTML files first using:
func (*gin.Engine).LoadHTMLFiles(files ...string)orfunc (*gin.Engine).LoadHTMLGlob(pattern string)
In your case with your provided directory structure:
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
}
答案2
得分: 0
根据文档,静态文件的服务代码如下:
r.StaticFS("/index.html", http.Dir("<your_directory_name>"))
英文:
Accorfing to Documents serving static file is as followings:
   r.StaticFS("/index.html", http.Dir("<your_directory_name>"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论