Go入门笔记35-Go gin使用

1、代码

package main

import (
	"encoding/json"
	"fmt"
	"net/http"

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

type User struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	Age  int    `json:"age"`
}

type postForm1 struct {
	UserId string   `json:"userid" form:"userid" binding:"required"`
	Page   []string `json:"page" form:"page" binding:"required"`
}

func main() {
	r := gin.Default()
	r.POST("/post", func(c *gin.Context) {

		id := c.Query("postid")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")

		fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)

		c.JSON(200, gin.H{
			"status":  "posted",
			"id":      id,
			"page":    page,
			"name":    name,
			"message": message,
		})
	})
	r.POST("/post1", func(c *gin.Context) {
		var form postForm1
		if c.BindJSON(&form) == nil {
			c.JSON(200, gin.H{
				"status": 200,
				"id":     form.UserId,
				"page":   form.Page,
			})
		}
		fmt.Printf("id: %s ", form.UserId)
	})
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.GET("/user/:name/:action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)
	})
	r.GET("/ping1", func(c *gin.Context) {

		jsonData := []byte(`{"msg":"this worked"}`)

		var v interface{}
		json.Unmarshal(jsonData, &v)
		data := v.(map[string]interface{})

		c.JSON(http.StatusOK, data)

	})

	r.Run(":8080")
}

注意Post Bind有两种方式如果是Form直接Bind,否则使用BindJson
错误解决办法
gin listen tcp: address 8000: missing port in address
端口前面加:
其中一个测试示例image

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值