• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Go语学习笔记 - 环境安装、接口测试 | Web框架Gin一

武飞扬头像
剑客阿良_ALiang
帮助1

学习笔记,写到哪是哪。

基础语法差不多了,需要开始实践到一下项目,先来web框架gin吧,做一个后端web服务。

在把项目搭建起来的过程中,我也要结合实际的工作经验,补充一些项目结构、开发组件上的理解。

项目地址:github地址

gin安装

先将gin安装一下,安装依赖go语言还是比较方便的。

在安装之前先配置一下goproxy。

命令如下:

  1.  
    go env -w GO111MODULE=on
  2.  
    go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/ //阿里代理
  3.  
    go env -w GOPROXY=https://goproxy.cn //七牛云代理

安装一下gin,命令如下:

go get github.com/gin-gonic/gin

Get请求测试

实现一个web服务还是比较简单的,创建一个router,绑定路由规则即可。先测试几个Get请求。

样例代码如下:

  1.  
    package main
  2.  
     
  3.  
    import (
  4.  
    "github.com/gin-gonic/gin"
  5.  
    "net/http"
  6.  
    )
  7.  
     
  8.  
    func main() {
  9.  
    router := gin.Default()
  10.  
    router.GET("/", func(context *gin.Context) {
  11.  
    context.String(http.StatusOK, "hello world")
  12.  
    })
  13.  
     
  14.  
    router.GET("/test/:name", func(context *gin.Context) {
  15.  
    name := context.Param("name")
  16.  
    context.String(http.StatusOK, "check param %s", name)
  17.  
    })
  18.  
     
  19.  
    router.GET("/test1", func(context *gin.Context) {
  20.  
    name := context.DefaultQuery("name", "张三")
  21.  
    gender := context.Query("gender")
  22.  
    context.String(http.StatusOK, "他叫%s,性别:%s", name, gender)
  23.  
    })
  24.  
     
  25.  
    router.Run(":8080")
  26.  
    }
学新通

执行结果

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
[GIN-debug] GET    /test/:name               --> main.main.func2 (3 handlers)
[GIN-debug] GET    /test1                    --> main.main.func3 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8080

[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend yo
u to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-
proxies for details.
[GIN-debug] Listening and serving HTTP on :8080

测试一下,这里我是用的接口测试工具为ApiPost

学新通

学新通

 学新通

注意

1、在使用context.DefaultQuery方法的时候,可以提供一个默认值。

2、除了可以使用":"来获取路径参数外,可以使用"*",可以匹配更多规则。我个人感觉我不会这么用get请求参数。

Post请求测试

Post请求是在项目中使用的比较多的,而且不管是使用form获取参数还是body,都十分常见。

同时返回的数据也不可能使用一行字符串,实际项目中还是使用json格式居多。

所以下面我使用form参数和body参数实现了一下post测试接口。

完成代码如下

  1.  
    package main
  2.  
     
  3.  
    import (
  4.  
    "encoding/json"
  5.  
    "fmt"
  6.  
    "github.com/gin-gonic/gin"
  7.  
    "io/ioutil"
  8.  
    "net/http"
  9.  
    )
  10.  
     
  11.  
    type Result struct {
  12.  
    Name string `json:"name"`
  13.  
    Age int `json:"age"`
  14.  
    }
  15.  
     
  16.  
    //反序列化为结构体对象
  17.  
    func parseJson(a string) Result {
  18.  
    fmt.Printf("原始字符串: %s\n", a)
  19.  
    var c Result
  20.  
    if err := json.Unmarshal([]byte(a), &c); err != nil {
  21.  
    fmt.Println("Error =", err)
  22.  
    return c
  23.  
    }
  24.  
    return c
  25.  
    }
  26.  
     
  27.  
    func main() {
  28.  
    router := gin.Default()
  29.  
    router.GET("/", func(context *gin.Context) {
  30.  
    context.String(http.StatusOK, "hello world")
  31.  
    })
  32.  
     
  33.  
    router.GET("/test/:name", func(context *gin.Context) {
  34.  
    name := context.Param("name")
  35.  
    context.String(http.StatusOK, "check param %s", name)
  36.  
    })
  37.  
     
  38.  
    router.GET("/test1", func(context *gin.Context) {
  39.  
    name := context.DefaultQuery("name", "张三")
  40.  
    gender := context.Query("gender")
  41.  
    context.String(http.StatusOK, "他叫%s,性别:%s", name, gender)
  42.  
    })
  43.  
     
  44.  
    router.POST("/testPost", func(context *gin.Context) {
  45.  
    name := context.PostForm("name")
  46.  
    nick := context.DefaultPostForm("nick", "leo")
  47.  
    context.JSON(http.StatusOK, gin.H{
  48.  
    "status": gin.H{
  49.  
    "code": http.StatusOK,
  50.  
    "success": true,
  51.  
    },
  52.  
    "name": name,
  53.  
    "nick": nick,
  54.  
    })
  55.  
    })
  56.  
     
  57.  
    router.POST("/testPost2", func(context *gin.Context) {
  58.  
    data, _ := ioutil.ReadAll(context.Request.Body)
  59.  
    fmt.Println(string(data))
  60.  
    context.JSON(http.StatusOK, gin.H{
  61.  
    "code": http.StatusOK,
  62.  
    "data": parseJson(string(data)),
  63.  
    })
  64.  
    })
  65.  
     
  66.  
    router.Run(":8080")
  67.  
    }
学新通

测试一下testPost和testPost2接口

学新通

学新通

注意

1、使用context.DefaultPostForm方法可以提供一个默认值。

2、可以使用gin.H方法构造json结构返回。

3、将获得打参数反序列化为结构体,这部分的代码使用到之前讲json解析的笔记。

小结

本篇笔记主要是对gin的简单使用,我希望把这个项目慢慢完善,比如项目结构优化(可以贴合mvc结构)、日志功能、配置文件、数据库操作、缓存操作、高并发设计等等。项目持续升级,从中慢慢熟悉go语言的项目结构。

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfhjcf
系列文章
更多 icon
同类精品
更多 icon
继续加载