go 语言 Gin框架 接收请求

文档地址:https://github.com/skyhee/gin-doc-cn#basic-router

get 请求方式:

package main

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

func main() {
	router := gin.Default()
    router.GET("/string/:name", func(c *gin.Context) {
    	name := c.Param("name")
    	fmt.Println("Hello %s", name)
		c.String(http.StatusOK, fmt.Sprintf("namne是: '%s'", name))
		//c.JSON(http.StatusOK, msg)
		//c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
		//c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })
    router.Run(":8080")
}

post 请求方式:

package main

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

func main() {
	router:= gin.Default()
	//form
	router.POST("/form", func(c *gin.Context) {
		type0 := c.DefaultPostForm("type", "alert")//可设置默认值
		msg := c.PostForm("msg")
		title := c.PostForm("title")
		fmt.Println("type is '%s', msg is '%s', title is '%s'", type0, msg, title)
		c.String(http.StatusOK, fmt.Sprintf("type is '%s', msg is '%s', title is '%s'", type0, msg, title))
	})
    router.Run(":8080")
}

数据自动解析绑定

package main

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


// Binding from JSON
type Login struct {
	User     string `form:"user" json:"user" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}


func main() {
	router:= gin.Default()
	// 绑定JSON的例子 ({"user": "manu", "password": "123"})
	router.POST("/loginJSON", func(c *gin.Context) {
		var json Login

		if c.BindJSON(&json) == nil {
			if json.User == "manu" && json.Password == "123" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})

	// 绑定普通表单的例子 (user=manu&password=123)
	router.POST("/loginForm", func(c *gin.Context) {
		var form Login
		// 根据请求头中 content-type 自动推断.
		if c.Bind(&form) == nil {
			if form.User == "manu" && form.Password == "123" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			}
		}
	})
	// 绑定多媒体表单的例子 (user=manu&password=123)
	/*
	router.POST("/login", func(c *gin.Context) {
		var form LoginForm
		// 你可以显式声明来绑定多媒体表单:
		// c.BindWith(&form, binding.Form)
		// 或者使用自动推断:
		if c.Bind(&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")
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值