golang/gin之接收、响应数据笔记

239 阅读2分钟

接收数据


import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
)

// http://127.0.0.1:9090/haha?user=zhangsan&user=李四
// 客户访问后获得用户的访问信息
func sayHello(c *gin.Context) {
	//拿一个user参数
	fmt.Println(c.Query("user"))
	//拿到多个查询相同的参数
	fmt.Println(c.GetQuery("user"))
	fmt.Println(c.QueryArray("user"))
	//如果用户没传,可以设置一个默认值
	fmt.Println(c.DefaultQuery("user", "123"))
}

// http://127.0.0.1:9090/liuliu/zhangsan/book
// 动态参数,根据请求格式自动获取参数
func _param(c *gin.Context) {
	//接收单个、多个参数
	fmt.Println(c.Param("user_id"))
	fmt.Println(c.Param("book_id"))
}

// 接收表单
func _form(c *gin.Context) {
	//接收键为name的表单
	fmt.Println(c.PostForm("name"))
	//接收多个键为name的表单
	fmt.Println(c.PostFormArray("name"))
	//如果用户没传,可以设置一个默认值,使用这个默认值
	fmt.Println(c.DefaultPostForm("name", "ok没毛病"))
	form, err := c.MultipartForm() //接收所有form参数,包括文件
	fmt.Println(form, err)
}

// 原始参数,接收到得到最原始的数据
func _raw(c *gin.Context) {
	//获取原始数据,需要用string转化
	n, _ := c.GetRawData()
	//获取请求头
	s := c.GetHeader("Content-Type")
	//如果请求头为application/json代表接收了json,则获取那个值
	switch s {
	case "application/json":
		//将json格式转换成结构体并输出出来
		type User struct {
			Name string `json:"name"`
			Age  int    `json:"age"`
		}
		var user User
		//将json内容放入结构体
		err := json.Unmarshal(n, &user)
		if err != nil {
			fmt.Println(err.Error())
		}
		fmt.Println(user)
	}
}

func main() {
	r := gin.Default()
	//谁在前面谁先匹配
	r.GET("/haha", sayHello)
	r.GET("/liuliu/:user_id", _param)
	r.GET("/liuliu/:user_id/:book_id", _param)
	r.GET("/form", _form)
	r.GET("/raw", _raw)
	r.Run(":9090")
}


响应数据


import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 传json
func sayHello(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "hello golang!",
		"data": gin.H{
			"abc":  "aaa",
			"abc2": "abc",
		},
	})
}

// 传HTML,可以传参哦
func _html(c *gin.Context) {
	c.HTML(200, "index.html", gin.H{"go": "go1"})
}

// 重定向,跳转到百度
func _baidu(c *gin.Context) {
	//301是永久重定向,就算你之后该了也不会再改到新地址,除非用户删除浏览器缓存
	//302是临时重定向,只会跳转请求一次
	c.Redirect(301, "https://www.baidu.com")
}

func main() {
	//返回默认的路由引擎
	r := gin.Default()
	//加载模板从本目录下加载
	r.LoadHTMLGlob("template/*")
	//网页请求的路径127.0.0.1/photo域名访问图片路径photo/tupian.png
	r.StaticFile("/photo", "photo/tupian.png")
	//网页请求的这个静态目录的前缀,第二个参数他是一个目录,前缀和之前不要重复
	r.StaticFS("/photo2", http.Dir("photo/"))
	//指定用户使用get请求访问/hello时,执行sayhello函数
	r.GET("/hello", sayHello)
	r.GET("/yeye", _html)
	//跳转到百度
	r.GET("/baidu", _baidu)
	//想处理不同的请求调用就行了
	r.GET("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "GET",
		})
	})
	r.POST("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "POST",
		})
	})
	r.PUT("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "PUT",
		})
	})
	r.DELETE("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"method": "DELETE",
		})
	})
	//http监听端口,一旦有"/hello"请求过来以后,直接跳转到sayHallo
	r.Run(":9090")
}