• 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

    本博客是个人工作中记录,遇到问题可以互相探讨,没有遇到的问题可能没有时间去特意研究,勿扰。
    另外建了几个QQ技术群:
    2、全栈技术群:616945527,加群口令abc123
    2、硬件嵌入式开发: 75764412
    3、Go语言交流群:9924600

    闲置域名www.nsxz.com出售(等宽等高字符四字域名)。
  • 相关阅读:
    每周总结03
    Servlet2
    每周总结02
    周总结4
    河北省重大需求征集系统每日进度6
    周总结3
    hadoop命令
    复习uml
    周总结2
    河北省重大需求征集系统每日进度5
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/15212897.html
Copyright © 2020-2023  润新知