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})

}

main函数通过LoadHTMLGlob加载文件夹下的所有静态页面,然后通过c.HTML直接渲染给浏览器,当携带数据收到浏览器post请求时,通过c.JSON返回给浏览器一串json字符串

看下模版代码

Check some colors

Red

Green

Blue

效果图如下:

b726b488bfe95e0ea463f3c18679bad9.png

125390d7942e2cf1f99b14b73f0d43cf.png

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")

}

前端代码如下:

Check some colors

user:

pwd:

1、效果如如下:

f658a6449c97f363ada05d12b4bb8ab0.png

当输入正确当用户名、密码后台就返回{"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$

看到控制台输出了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")

}

看下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})

})

输入http://127.0.0.1:8080/someXML

输出

200

hey

yaml

r.GET("/someYAML", func(c *gin.Context) {

c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})

})

输入http://127.0.0.1:8080/someYAML

输出

message: hey

status: 200

ProtoBuf

可以看我之前写关于protobuf的博客

golang基础-protobuf使用

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)

})

这里只列出官方的一个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")

}

AsciiJSON

我们还可以返回具有编码格式对数据

r.GET("/someJSON", func(c *gin.Context) {

data := map[string]interface{}{

"lang": "GO语言",

"tag": "
",

}

// will output : {"lang":"GOu8bedu8a00","tag":"u003cbru003e"}

c.AsciiJSON(http.StatusOK, data)

})

效果图如下:

0168c872738ec9ed4c1be4eaac8856f2.png

1a94dc88aa1c18044bef53bddb202f00.png

PureJSON

通常,JSON用其unicode实体替换特定的HTML字符,例如<.003c>

r.GET("/json", func(c *gin.Context) {

c.JSON(200, gin.H{

"html": "Hello, world!",

})

})

9fd329f33ae03e80f7d85aa5eb0108c9.png

8126855a66b4e86da0e35302fe00d9d9.png

当然如果我们使用PureJSON,就可以直接返回字符串显示了,不用在编码了

41d7dad6d60521e9c7534129fdf8f628.png