Home > OS >  how to serve html file with using router in gin?
how to serve html file with using router in gin?

Time:12-28

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

CodePudding user response:

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) or
  • func (*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
}

CodePudding user response:

Accorfing to Documents serving static file is as followings:

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

Documents reference

  •  Tags:  
  • go
  • Related