- Using the gin framework,return string types,JSON types,XML types ,struct types,JSONP type data.
- the use of template and template syntax
- Access mysql using the ORM packag
#1.Custom template function
#2.template nesting
#3.static file service
#Define the function body
// Time stamp converted to data function
func UnixToTime(timestamp int) string {
fmt.Println(timestamp)
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05")
}
#Register a function with gin
//custom template function
r.SetFuncMap(template.FuncMap{
"UnixToTime": UnixToTime,
})
#create main.go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"html/template"
"net/http"
"time"
)
// Time stamp converted to data function
func UnixToTime(timestamp int) string {
fmt.Println(timestamp)
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05")
}
func main() {
r := gin.Default()
//custom template function
r.SetFuncMap(template.FuncMap{
"UnixToTime": UnixToTime,
})
//Configure template engine to load everything in the template
r.LoadHTMLGlob("templates/**/*")
//Render templates using the gin framework
r.GET("/news", func(c *gin.Context) {
c.HTML(http.StatusOK, "news/index.html", gin.H{
"title": "news page",
"date": 1667538183,
})
})
r.Run(":8088")
}
#create news/index.html
{{define "news/index.html"}}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!--Before conversion-->
<p>
{{.date}}
</p>
<!--After conversion-->
{{UnixToTime .date}}
{{Add 3 3}}
</body>
</html>
{{end}}
go run main.go
//Listening and serving HTTP on :8088
//[GIN] 2022/11/04 - 01:17:42 | 200 | 712.682µs | 127.0.0.1 | GET //"/news"
http://localhost:8088/news
//1667538183
//2022-11-04 01:03:03 6
#2.template nesting
{{template "public/page_header.html" .}}
#3.static file service
#Register a static file router with gin
//The front static indicates the route,and the back static indicates the path
r.Static("/static","./static")