返回json

返回json

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	r.GET("/json", func(context *gin.Context) {
		//使用map
		//data := map[string]interface{}{
		//	"name":"zzz",
		//	"msg":"hello world",
		//	"age":19,
		//}
		data := gin.H{
			"name": "zzz",
			"msg": "hello world",
			"age": 19}
		context.JSON(http.StatusOK, data)

	})
	r.Run(":9000")
}

结构体

//结构体
	type Msg struct {
		Name string
		Age int
	}
	msg := Msg{Name: "zc",Age: 10}
	r.GET("/msg_json", func(context *gin.Context) {
		context.JSON(http.StatusOK,msg)
	})

获取参数

获取querystring参数

querystring指的是URL中?后面携带的参数,例如:/user/search?username=小王子&address=沙河。 获取请求的querystring参数的方法如下:

func main() {
	r :=gin.Default()
	r.GET("/data", func(context *gin.Context) {
		//获取浏览器那边携带的query string
		//name := context.Query("query")
		//name := context.DefaultQuery("query","some")//取不到,就用默认的值浏览器xxxx=\ 默认= {"name":"some"}
		name,ok:=context.GetQuery("query")
		if !ok{
			name="soml"
		}
		context.JSON(http.StatusOK,gin.H{
			"name":name,
		})
	})
	r.Run(":9000")
}

获取form参数

r := gin.Default()
	r.LoadHTMLFiles("./login.html","./index.html")
	r.GET("/login", func(context *gin.Context) {
		context.HTML(http.StatusOK, "login.html", nil)

	})
	r.POST("/login", func(context *gin.Context) {
		//获取form表单提交的信息
		//username:= context.PostForm("username")
		//password:= context.PostForm("password")
		//username:= context.DefaultPostForm("username","xxxxx")
		//password:= context.DefaultPostForm("password","xxxxaaa ")
		username,ok:= context.GetPostForm("username")
		if !ok {
			username = "失败"
		}
		password,ok:= context.GetPostForm("username")
		if !ok {
			password = "失败"
		}
		context.HTML(http.StatusOK, "index.html", gin.H{
			"name": username,
			"pwd":password,
		})

	})
	r.Run(":9000")
}

获取json参数

当前端请求的数据通过JSON提交时,例如向/json发送一个POST请求,则获取请求参数的方式如下:

r.POST("/json", func(c *gin.Context) {
	// 注意:下面为了举例子方便,暂时忽略了错误处理
	b, _ := c.GetRawData()  // 从c.Request.Body读取请求数据
	// 定义map或结构体
	var m map[string]interface{}
	// 反序列化
	_ = json.Unmarshal(b, &m)

	c.JSON(http.StatusOK, m)
})

获取路径参数

r := gin.Default()
	r.GET("/user/:name/:age", func(context *gin.Context) {
		name := context.Param("name")
		age := context.Param("age")
		context.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  age,
		})

	})
	r.Run(":9000")

绑定参数

为了能够更方便的获取请求相关参数,提高开发效率,我们可以基于请求的Content-Type识别请求数据类型并利用反射机制自动提取请求中QueryStringform表单JSONXML等参数到结构体中。 下面的示例代码演示了.ShouldBind()强大的功能,它能够基于请求自动提取JSONform表单QueryString类型的数据,并把值绑定到指定的结构体对象。

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserInfo struct {
	Username string `form:"username",json:"username"`
	Password string `form:"password",json:"password"`
}

func main() {

	r := gin.Default()
	r.GET("/user", func(context *gin.Context) {
		//username := context.Query("username")
		//password := context.Query("password")
		//user := UserInfo{Username: username, Password: password}
		//context.JSON(http.StatusOK, gin.H{
		//	"msg": "ok",
		//	"user":user,
		//})
		var u UserInfo
		err := context.ShouldBind(&u)
		if err != nil {
			context.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v", u)
			context.JSON(http.StatusOK, gin.H{
				"username": u.Username,
				"password": u.Password,
			})
		}

	})
	r.POST("/user", func(context *gin.Context) {
		var u UserInfo
		err := context.ShouldBind(&u)
		if err != nil {
			context.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		} else {
			fmt.Printf("%#v", u)
			context.JSON(http.StatusOK, "ok")
		}

	})
	r.Run(":9000")

}

ShouldBind会按照下面的顺序解析请求中的数据完成绑定:

  1. 如果是 GET 请求,只使用 Form 绑定引擎(query)。
  2. 如果是 POST 请求,首先检查 content-type 是否为 JSONXML,然后再使用 Formform-data)。

上传文件

func main() {
	r:=gin.Default()
	r.LoadHTMLFiles("./index.html")
	r.GET("/index", func(context *gin.Context) {		context.HTML(http.StatusOK,"index.html",nil)
	})
	r.POST("/upload", func(context *gin.Context) {
		//从请求中读取文件
		f,err:=context.FormFile("f1")
		if err != nil {
			context.JSON(http.StatusBadRequest,gin.H{
				"error":err.Error(),
			})
		}else {
			//将读取到的文件保存到本地
			dst := path.Join("./",f.Filename)

			context.SaveUploadedFile(f,dst)
			context.JSON(http.StatusOK,gin.H{
				"status":"ok",
			})
		}
	})
	r.Run(":9000")

}

上传多个文件

func main() {
	router := gin.Default()
	// 处理multipart forms提交文件时默认的内存限制是32 MiB
	// 可以通过下面的方式修改
	// router.MaxMultipartMemory = 8 << 20  // 8 MiB
	router.POST("/upload", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		files := form.File["file"]

		for index, file := range files {
			log.Println(file.Filename)
			dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index)
			// 上传文件到指定的目录
			c.SaveUploadedFile(file, dst)
		}
		c.JSON(http.StatusOK, gin.H{
			"message": fmt.Sprintf("%d files uploaded!", len(files)),
		})
	})
	router.Run()
}

重定向

r.GET("/data", func(context *gin.Context) {
		context.Redirect(http.StatusMovedPermanently,"https://www.liwenzhou.com/")

	})
	r.GET("/a", func(context *gin.Context) {
		//跳转到/b对应的路由处理函数
		context.Request.URL.Path="/b"
		r.HandleContext(context) //继续后续的处理

	})
	r.GET("/b", func(context *gin.Context) {

		context.JSON(http.StatusOK,gin.H{
			"msg":"b",
		})
	})

路由


func main() {
	r := gin.Default()
	r.Any("/user", func(context *gin.Context) {
		switch context.Request.Method {
		case "GET":
			context.JSON(http.StatusOK, gin.H{
				"method": "GET",
			})
		case "POST":
			context.JSON(http.StatusOK, gin.H{
				"method": "POST",
			})
		}

	})
	r.NoRoute(func(context *gin.Context) {
		context.JSON(http.StatusNotFound, gin.H{
			"msg": "页面不存在",
		})
	})
	
	r.Run(":9000")
}

路由组

//路由组
shopGroup := r.Group("/shop")
	{
		shopGroup.GET("/index", func(c *gin.Context) {...})
		shopGroup.GET("/cart", func(c *gin.Context) {...})
		shopGroup.POST("/checkout", func(c *gin.Context) {...})
		// 嵌套路由组
		xx := shopGroup.Group("xx")
		xx.GET("/oo", func(c *gin.Context) {...})
	}
posted @ 2021-03-31 21:20  小子,你摊上事了  阅读(111)  评论(0)    收藏  举报