gin(Http请求和参数解析)


1.engine实例的创建

func main(){
	engine := gin.Default()
	//定义个GET请求
	/*engine.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello World!")
	})*/
	//定义通用方法 Handle
	engine.Handle("GET","/hello", func(context *gin.Context) {
		path := context.FullPath() //获取请求路径  /hello
		fmt.Println(path)

		name := context.DefaultQuery("name","zhangsan")
		fmt.Println(name)

		//页面打印
		context.Writer.Write([]byte("Hello ,"+name))
          
                context.JSON(http.StatusOK,gin.H{"code":http.StatusOK,"msg":"操作成功"}) //返回 JSON
}) engine.Run() }

2.获取参数

id := context.Query("id") //获取URL后面的参数
name := context.DefaultQuery("name","张三丰") //获取URL后面的参数 ,可以设置默认值
username := c.PostForm("username")//从表单中查询参数
sex := c.DefaultPostForm("sex","男") //可以设置默认值
name := context.Params("name") //获取URL绑定参数

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM