golangWeb框架---github.com/gin-gonic/gin学习五(模版渲染、返回数据的格式)
文章目录
Bind HTML checkboxes
Multipart/Urlencoded 绑定
XML, JSON, YAML and ProtoBuf rendering
json
xml
yaml
ProtoBuf
JSONP
AsciiJSON
PureJSON
Bind HTML checkboxes
学web最起码要搞一个浏览器get请求后端,然后后端渲染html页面,然后提交post请求,然后后端返回结果
代码很简单直接上后端代码
package main
import (
"github.com/gin-gonic/gin"
)
type myForm struct {
Colors []string `form:"colors[]"`
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("template/*")
r.GET("/", indexHandler)
r.POST("/", formHandler)
r.Run(":8080")
}
func indexHandler(c *gin.Context) {
c.HTML(200, "view.html", nil)
}
func formHandler(c *gin.Context) {
var fakeForm myForm
c.Bind(&fakeForm)
c.JSON(200, gin.H{"color": fakeForm.Colors})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
main函数通过LoadHTMLGlob加载文件夹下的所有静态页面,然后通过c.HTML直接渲染给浏览器,当携带数据收到浏览器post请求时,通过c.JSON返回给浏览器一串json字符串
看下模版代码
<form action="/" method="POST">
<p>Check some colors</p>
<label for="red">Red</label>
<input type="checkbox" name="colors[]" value="red" id="red" />
<label for="green">Green</label>
<input type="checkbox" name="colors[]" value="green" id="green" />
<label for="blue">Blue</label>
<input type="checkbox" name="colors[]" value="blue" id="blue" />
<input type="submit" />
</form>
1
2
3
4
5
6
7
8
9
10
效果图如下:
Multipart/Urlencoded 绑定
我们在看一个例子,后端代码如下:
package main
import (
"github.com/gin-gonic/gin"
)
type LoginForm struct {
User string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.LoadHTMLGlob("template/*")
router.GET("/login", func(context *gin.Context) {
context.HTML(200, "view.html", nil)
})
router.POST("/login", func(c *gin.Context) {
var form LoginForm
if c.ShouldBind(&form) == nil {
if form.User == "user" && form.Password == "password" {
c.JSON(200, gin.H{"status": "you are logged in"})
} else {
c.JSON(401, gin.H{"status": "unauthorized"})
}
}
})
router.Run(":8080")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
前端代码如下:
<form action="" method="POST">
<p>Check some colors</p>
user:<input type="text" name="user" id="red" />
pwd:<input type="text" name="password" id="green" />
<input type="submit" />
</form>
1
2
3
4
5
6
7
8
1、效果如如下:
当输入正确当用户名、密码后台就返回{"status":"you are logged in"}
2、我们还可以使用crul进行操作
zhiliaodeMBP:go zhiliao$ curl -v --form user=user --form password=password http://localhost:8080/login
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /login HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 248
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------15f5806540b372ce
>
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Thu, 20 Sep 2018 11:52:25 GMT
< Content-Length: 30
<
* Connection #0 to host localhost left intact
zhiliaodeMBP:go zhiliao$
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
看到控制台输出了200正确到状态码
XML, JSON, YAML and ProtoBuf rendering
json
我们之前总结过很多返回json的,这里我就直接贴代码即可
package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/testdata/protoexample"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/someJSON", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/moreJSON", func(c *gin.Context) {
// You also can use a struct
var msg struct {
Name string `json:"user"`
Message string
Number int
}
msg.Name = "Lena"
msg.Message = "hey"
msg.Number = 123
c.JSON(http.StatusOK, msg)
})
r.Run(":8080")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
看下json测试效果:
输入http://127.0.0.1:8080/someJSON
输出{"message":"hey","status":200}
输入http://127.0.0.1:8080/moreJSON
输出{"user":"Lena","Message":"hey","Number":123}
xml
看下xml测试效果:
r.GET("/someXML", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
1
2
3
输入http://127.0.0.1:8080/someXML
输出
<map>
<status>200</status>
<message>hey</message>
</map>
1
2
3
4
yaml
r.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
1
2
3
输入http://127.0.0.1:8080/someYAML
输出
message: hey
status: 200
1
2
ProtoBuf
可以看我之前写关于protobuf的博客
golang基础-protobuf使用
golang基础-RPC结合Protobuf实例、GRPC实例
r.GET("/someProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
// The specific definition of protobuf is written in the testdata/protoexample file.
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
// Note that data becomes binary data in the response
// Will output protoexample.Test protobuf serialized data
c.ProtoBuf(http.StatusOK, data)
})
1
2
3
4
5
6
7
8
9
10
11
12
这里只列出官方的一个demo,后续我会针对gin中如何使用protobuf在另开博客
JSONP
如果对跨域还不是很清楚,可以参考我如下对博客
Ajax跨域–Ajax跨域
如下对这个例子我就直接贴出官方demo即可,就不去验证了,时间比较紧,后续用到在补充进来即可
Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists
func main() {
r := gin.Default()
r.GET("/JSONP?callback=x", func(c *gin.Context) {
data := map[string]interface{}{
"foo": "bar",
}
//callback is x
// Will output : x({\"foo\":\"bar\"})
c.JSONP(http.StatusOK, data)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
AsciiJSON
我们还可以返回具有编码格式对数据
r.GET("/someJSON", func(c *gin.Context) {
data := map[string]interface{}{
"lang": "GO语言",
"tag": "<br>",
}
// will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
c.AsciiJSON(http.StatusOK, data)
})
1
2
3
4
5
6
7
8
9
10
11
效果图如下:
PureJSON
通常,JSON用其unicode实体替换特定的HTML字符,例如<.003c。如果要按字面编码这些字符,可以使用PureJSON代替。这个特性在GO 1.6和更低版本中不可用。
r.GET("/json", func(c *gin.Context) {
c.JSON(200, gin.H{
"html": "<b>Hello, world!</b>",
})
})
1
2
3
4
5
当然如果我们使用PureJSON,就可以直接返回字符串显示了,不用在编码了
————————————————
版权声明:本文为CSDN博主「丙申」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u013210620/java/article/details/82792190
posted on 2020-05-25 21:09 ExplorerMan 阅读(518) 评论(0) 编辑 收藏 举报