• golang-gin框架使用1


    一、处理请求,响应

    \

    包含不同请求类型的处理,response返回类型,类型绑定,和html模板和静态文件处理。

    RequestResponse
    curl -L ‘http://localhost:8080/ping?name=xwp’
    curl -L --header ‘Content-Type: application/x-www-form-urlencoded’ --data-urlencode ‘usern=xwp’ --data-urlencode ‘password=xwp123’ http://localhost:8080/login
    curl -L --request DELETE ‘http://localhost:8080/user/3’
    curl -L ‘http://localhost:8080/hello?id=27&username=xwp’
    curl -L ‘http://localhost:8080/register’ --header ‘Content-Type: application/x-www-form-urlencoded’ --data-urlencode ‘name=xwp’ --data-urlencode ‘password=xwp123’ --data-urlencode ‘phone=8772463’
    curl -L ‘http://localhost:8080/addstudent’ --header ‘Content-Type: application/json’ --data ‘{“id”: 100,“username”: “yjj”}’
    curl -L http://localhost:8080/jsonstruct
    http://localhost:8080/testhtml

    main.go

    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    
    	"github.com/gin-gonic/gin"
    )
    
    func main() {
    	engine := gin.Default()
    	// curl -L 'http://localhost:8080/ping?name=xwp'
    	engine.GET("/ping", func(c *gin.Context) {
    		// c.Writer.Write([]byte("Hello, gin!\n"))
    		query_res := c.DefaultQuery("name", "unknow")
    
    		fmt.Printf("query_res: %v\n", query_res)
    		c.JSON(http.StatusOK, gin.H{
    			"message":  "pong",
    			"fullPath": c.FullPath(),
    		})
    	})
    	// curl -L --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'usern=xwp' --data-urlencode 'password=xwp123' http://localhost:8080/login
    	engine.POST("/login", func(c *gin.Context) {
    		var user, password string
    		user, b := c.GetPostForm("user")
    		if !b {
    			c.Writer.Write([]byte("username is empty, please try again!\n"))
    			return
    		}
    		password = c.PostForm("password")
    		fmt.Printf("username: %v password: %v\n", user, password)
    		c.Writer.Write([]byte(fmt.Sprintf("%v login successfully!", user)))
    	})
    	// curl -L --request DELETE 'http://localhost:8080/user/3'
    	engine.DELETE("/user/:id", func(c *gin.Context) {
    		id := c.Param("id")
    		fmt.Printf("User id: %v\n", id)
    		c.JSON(http.StatusOK, gin.H{
    			"message": fmt.Sprintf("user %v has been deleted", id),
    		})
    	})
    	// GET提交表单:curl -L 'http://localhost:8080/hello?id=27&username=xwp'
    	engine.GET("/hello", func(c *gin.Context) {
    		var s Student
    		if err := c.ShouldBindQuery(&s); err != nil {
    			log.Fatal(err)
    			return
    		}
    		fmt.Printf("Id: %v\n", s.Id)
    		fmt.Printf("Username: %v\n", s.Username)
    		c.Writer.Write([]byte(fmt.Sprintf("hello %v\n", s.Username)))
    	})
    	// POST提交表单: curl -L 'http://localhost:8080/register' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'name=xwp' --data-urlencode 'password=xwp123' --data-urlencode 'phone=8772463'
    	engine.POST("/register", func(c *gin.Context) {
    		var register Register
    		if err := c.ShouldBind(&register); err != nil {
    			log.Fatal(err)
    			return
    		}
    		fmt.Printf("Name: %v\n", register.Name)
    		fmt.Printf("Password: %v\n", register.Password)
    		fmt.Printf("Phone: %v\n", register.Phone)
    		c.Writer.Write([]byte(register.Name + " registe successfully!"))
    	})
    	// POST提交json数据表单: curl -L 'http://localhost:8080/addstudent' --header 'Content-Type: application/json' --data '{"id": 100,"username": "yjj"}'
    	engine.POST("/addstudent", func(c *gin.Context) {
    		var student Student
    		if err := c.BindJSON(&student); err != nil {
    			log.Fatal(err)
    			return
    		}
    		fmt.Printf("student.Id: %v\n", student.Id)
    		c.Writer.Write([]byte(fmt.Sprintf("%v add successfully!\n", student.Username)))
    	})
    	// resopnse以json格式返回一个结构体对象  curl -L http://localhost:8080/jsonstruct
    	engine.GET("/jsonstruct", func(c *gin.Context) {
    		stu1 := Student{Id: 5378, Username: "Lenyu"}
    		c.JSON(http.StatusOK, &stu1)
    	})
    	// 返回一个html  curl -L http://localhost:8080/testhtml
    	engine.LoadHTMLGlob("./html/*")
    	engine.Static("static", "static")
    	engine.GET("testhtml", func(c *gin.Context) {
    		fullPath := c.FullPath()
    		c.HTML(http.StatusOK, "index.html", gin.H{
    			"fullPath": fullPath,
    			"title":    "gin教程",
    		})
    	})
    	engine.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
    }
    
    type Student struct {
    	Id       int    `form:"id"`
    	Username string `form:"username"`
    }
    type Register struct {
    	Name     string `form:"name"`
    	Phone    string `form:"phone"`
    	Password string `form:"password"`
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103

    二、模块化开发和中间件定义&使用

    定义RouterGroup,定义中间件FullPathAndMethod(),打印请求路径和请求方法并返回响应状态码。

    main.go

    package main
    
    import (
    	"fmt"
    
    	"github.com/gin-gonic/gin"
    )
    
    func main() {
    	// 模块化开发
    	// 用户注册: /user/register
    	// 用户登录: /user/login
    	// 用户信息: /user/info
    	// 用户删除: /user/id
    	engine := gin.Default()
    
    	rg := engine.Group("/user")
    	rg.POST("/register", FullPathAndMethod(), registerHandler)
    	rg.POST("/login", loginHandler)
    	rg.DELETE("/:id", FullPathAndMethod(), deleteHandler)
    	rg.GET("/info", FullPathAndMethod(), infoHandler)
    	engine.Run()
    }
    func registerHandler(c *gin.Context) {
    	fullPath := c.FullPath()
    	if _, err := c.Writer.WriteString("FullPath: " + fullPath); err != nil {
    		fmt.Printf("Write err: %v", err)
    		return
    	}
    	fmt.Println("registerHandler handler")
    }
    func loginHandler(c *gin.Context) {
    	fullPath := c.FullPath()
    	if _, err := c.Writer.WriteString("FullPath: " + fullPath); err != nil {
    		fmt.Printf("Write err: %v", err)
    		return
    	}
    }
    func deleteHandler(c *gin.Context) {
    	fullPath := c.FullPath()
    	id := c.Param("id")
    	if _, err := c.Writer.WriteString("FullPath: " + fullPath + "\nDelete user id: " + id); err != nil {
    		fmt.Printf("Write err: %v", err)
    		return
    	}
    }
    func infoHandler(c *gin.Context) {
    	fullPath := c.FullPath()
    	if _, err := c.Writer.WriteString("FullPath: " + fullPath); err != nil {
    		fmt.Printf("Write err: %v", err)
    		return
    	}
    }
    
    // write an middleware to print request url fullpath and request method.
    func FullPathAndMethod() gin.HandlerFunc {
    	return func(c *gin.Context) {
    		fullPath := c.FullPath()
    		method := c.Request.Method
    		fmt.Printf("fullPath: %v\n", fullPath)
    		fmt.Printf("method: %v\n", method)
    		c.Next()
    		// 打印处理响应完成后的状态码
    		httpCode := c.Writer.Status()
    		fmt.Printf("响应状态码: %v\n", httpCode)
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
  • 相关阅读:
    ZigBee 3.0理论教程-通用-1-01:概述
    qml var类型详解
    从0开始启动一个Django的docker服务
    看看面试要价25K的软件测试工程师,技术面都问他些什么问题?我上我也行
    【多线程】线程安全问题
    集成学习方法之随机森林-入门
    小型时间继电器ST3PA-C DC24V 带插座PF085A 导轨安装 JOSEF约瑟
    java 如何快速实现异步调用方法
    前端发送请求,显示超时取消
    【无标题】
  • 原文地址:https://blog.csdn.net/qq_46480020/article/details/133801957