Keep Your main.go simple
GO_WEB/ # 示意圖
├── controller
│ └──homeController
├── entity
│ └──user.go
├── template
│ └──index.html
├── main.go
<!DOCTYPE html>
<html>
<head><title>Iron Man</title></head>
<body>
<h1>{{.Name}}</h1>
<p>{{.Age}}</p>
<p>{{.Introduce}}</p>
</body>
</html>
type
來對我們自己闖造的型別進行自訂義key
package entity
type User struct {
Name string `json:"name"`
Introduce string `json:"introduce"`
Age int `json:"Age"`
}
HTML()
去對 index.html
做渲染package controller
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/kevinjone25/go_web/entity"
)
func Home(c *gin.Context) {
data := new(entity.User)
data.Age = 18
data.Introduce = "Hi! I'm Iron Man!!!"
data.Name = "Iron Man"
c.HTML(http.StatusOK, "index.html", data)
}
service.LoadHTMLGlob("template/*")
在告訴 server
說我應該要去那裡尋找渲染的檔案package main
import (
"github.com/gin-gonic/gin"
"github.com/kevinjone25/go_web/controller"
)
func main() {
server := gin.Default()
server.LoadHTMLGlob("template/*")
server.GET("/home", controller.Home)
server.Run()
}
go run main.go
就可以看到 server啟動的圖片啦,如果想要家bootstrap 或 tailwind 的朋友也可以自己加上去
小心有沒引入的package喔