The following describes the return types as follows:
- [ ]byte和string
- JSON format
- HTML template rendering
- Static resource settings
background
In the previous courses, we have learned and mastered multiple types of network requests and processing, and also mastered the operation of submitting data and binding structures. We all know that a complete request includes three steps: request, request processing, and result return. After the server finishes processing the request, the result will be returned to the client.
In the gin framework, multiple request data formats are supported.
[ ]byte
In the previous course cases, the format of the request return data we used uniformly was [ ]byte. Write [ ]byte data through context, Writer, and Write methods. The coded case looks like this:
package main
import "github.com/gin-gonic/gin"
func main() {
engine := gin.Default()
engine.GET("/byte", func(c *gin.Context) {
fullPath := c.FullPath()
c.Writer.Write([]byte(fullPath))
})
engine.Run()
}
string
engine.GET("/string", func(c *gin.Context) {
fullPath := c.FullPath()
c.Writer.WriteString(fullPath)
})
Here writer is an attribute in the context structure, and the type is a type of ResponseWriter.
type Context struct {
writermem responseWriter
Request *http.Request
Writer ResponseWriter
}
ResponseWriter is an interface type, which includes http.ResponseWriter, which is under the go standard library http package, and there are a series of methods here. The c.Writer method used above is a method under http.ResponseWriter.
type ResponseWriter interface {
http.ResponseWriter
http.Hijacker
http.Flusher
http.CloseNotifier
Status() int
Size() int
WriteString(string) (int, error)
Written() bool
WriteHeaderNow()
Pusher() http.Pusher
}
JSON
In addition to using the context.Writer object to return data of type byte and string. In project development, the JSON format specification is more commonly used. In order to make it easier for developers to use the framework for project development, gin directly supports assembling the returned data into JSON format for return.
The JSON method contained in the context in the gin framework can convert the data of the structure type into structured data in JSON format, and then return it to the client.
The following are two ways to demonstrate, one is to convert map type data into json, and secondly, it can also be converted into json format through structure type.
The map type programming call is as follows:
engine.GET("/map", func(c *gin.Context) {
fullPath := c.FullPath()
c.JSON(http.StatusOK, map[string]interface{}{
"code": 1,
"msg": "ok",
"data": fullPath,
})
})
In this way, the data format of the simplest map type is converted into json, and then returned to the front end.
The struct type programming call is as follows:
During real project development, there are often many structures, and the data corresponding to the value type of the structure should be returned directly to the front end.
Usually, the three data definitions of code, message and data are used as a general structure such as response.
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func delStructHandler(c *gin.Context) {
fullPath := "请求路径" + c.FullPath()
resp := Response{
Code: 1,
Message: "ok",
Data: fullPath,
}
c.JSON(http.StatusOK, &resp)
//第二个参数是interface类型,这里需要取值类型的地址
}
type Response struct {
Code int
Message string
Data interface{} //由于类型不确定,那么使用万能类型,interface类型
}
func main() {
engine := gin.Default()
engine.GET("/struct", delStructHandler)
engine.Run()
}
Html
In the gin framework, it supports direct loading of html pages or html templates, so that they can be rendered in the front end.
Here you need to create the html directory first, and all the html files are placed under the directory. Gin needs to load these files before using them.
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func htmlHandler(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
//第二个参数是interface类型,这里需要取值类型的地址
}
func main() {
engine := gin.Default()
//指明要加载的html文件所在的目录,这样就将html目录下面所有的文件可以让gin访问
engine.LoadHTMLGlob("C:\\Users\\W10\\GolandProjects\\day1\\gin\\bilibli\\html\\*")
engine.GET("/html", htmlHandler)
engine.Run()
}
Can this html page return some data from the background server to the html page?
This requires the use of a template language. To pass a variable to the index.html page for display, this requires the use of a template language to define variables in the html page. double curly braces + variable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>gin学习</h1>
{
{.fullPath}}
</body>
</html>
defined in this page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{
{.title}</title>
</head>
<body>
<h1>gin学习</h1>
{
{.fullPath}}
</body>
</html>
-------------------------------------------------------------------------------------------------------------------------
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func htmlHandler(c *gin.Context) {
fullPath := c.FullPath()
c.HTML(http.StatusOK, "index.html", gin.H{
"fullPath": fullPath,
"title": "gin学习",
})
//这样就将服务器端的变量传递到html页面当中了
}
func main() {
engine := gin.Default()
//指明要加载的html文件所在的目录,这样就将html目录下面所有的文件可以让gin访问
engine.LoadHTMLGlob("C:\\Users\\W10\\GolandProjects\\day1\\gin\\bilibli\\html\\*")
engine.GET("/html", htmlHandler)
engine.Run()
}
The above is the use of template language in html for data transfer and data display.
load static image
During the development process, the same type of resources are often created under the same directory.
The gin framework must first set the directory of the static resource when loading the static resource.
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func htmlHandler(c *gin.Context) {
fullPath := c.FullPath()
c.HTML(http.StatusOK, "index.html", gin.H{
"fullPath": fullPath,
"title": "gin学习",
})
//这样就将服务器端的变量传递到html页面当中了
}
func main() {
engine := gin.Default()
//指明要加载的html文件所在的目录,这样就将html目录下面所有的文件可以让gin访问
engine.LoadHTMLGlob("C:\\Users\\W10\\GolandProjects\\day1\\gin\\bilibli\\html\\*")
//第一个参数代表客户端请求的http路径,第二个参数表示本地工程的路径
engine.Static("/img", "../image")
engine.GET("/html", htmlHandler)
engine.Run()
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{
{.title}}</title>
</head>
<body>
<h1>gin学习</h1>
{
{.fullPath}}
<div align="center">
<img src="C:\Users\W10\GolandProjects\day1\gin\bilibli\image\test.jpg">
</div>
</body>
</html>