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

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

学习笔记,写到哪是哪。


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


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


项目地址:github地址


gin安装

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


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


命令如下:


go env -w GO111MODULE=on

go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/   //阿里代理

go env -w GOPROXY=https://goproxy.cn   //七牛云代理

安装一下gin,命令如下:


go get github.com/gin-gonic/gin

Get请求测试

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


样例代码如下:


package main
import (
  "github.com/gin-gonic/gin"
  "net/http"
)
func main() {
  router := gin.Default()
  router.GET("/", func(context *gin.Context) {
  context.String(http.StatusOK, "hello world")
  })
  router.GET("/test/:name", func(context *gin.Context) {
  name := context.Param("name")
  context.String(http.StatusOK, "check param %s", name)
  })
  router.GET("/test1", func(context *gin.Context) {
  name := context.DefaultQuery("name", "张三")
  gender := context.Query("gender")
  context.String(http.StatusOK, "他叫%s,性别:%s", name, gender)
  })
  router.Run(":8080")
}

执行结果


[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

image.png


image.png


image.png



注意


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


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


Post请求测试

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


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


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


完成代码如下


package main
import (
  "encoding/json"
  "fmt"
  "github.com/gin-gonic/gin"
  "io/ioutil"
  "net/http"
)
type Result struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}
//反序列化为结构体对象
func parseJson(a string) Result {
  fmt.Printf("原始字符串: %s\n", a)
  var c Result
  if err := json.Unmarshal([]byte(a), &c); err != nil {
  fmt.Println("Error =", err)
  return c
  }
  return c
}
func main() {
  router := gin.Default()
  router.GET("/", func(context *gin.Context) {
  context.String(http.StatusOK, "hello world")
  })
  router.GET("/test/:name", func(context *gin.Context) {
  name := context.Param("name")
  context.String(http.StatusOK, "check param %s", name)
  })
  router.GET("/test1", func(context *gin.Context) {
  name := context.DefaultQuery("name", "张三")
  gender := context.Query("gender")
  context.String(http.StatusOK, "他叫%s,性别:%s", name, gender)
  })
  router.POST("/testPost", func(context *gin.Context) {
  name := context.PostForm("name")
  nick := context.DefaultPostForm("nick", "leo")
  context.JSON(http.StatusOK, gin.H{
    "status": gin.H{
    "code":    http.StatusOK,
    "success": true,
    },
    "name": name,
    "nick": nick,
  })
  })
  router.POST("/testPost2", func(context *gin.Context) {
  data, _ := ioutil.ReadAll(context.Request.Body)
  fmt.Println(string(data))
  context.JSON(http.StatusOK, gin.H{
    "code": http.StatusOK,
    "data": parseJson(string(data)),
  })
  })
  router.Run(":8080")
}

测试一下testPost和testPost2接口


image.png


image.png


注意


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


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


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


Go语学习笔记 - Json解析 | 从零开始Go语言_剑客阿良_ALiang的博客-CSDN博客_go语言json对象


小结

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


相关文章
|
11天前
|
存储 Go
Go to Learn Go之接口
Go to Learn Go之接口
25 7
|
13天前
|
Go
Go 语言接口
Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。 接口可以让我们将不同的类型绑定到一组公共的方法上,从而实现多态和灵活的设计。
|
2月前
|
存储 缓存 NoSQL
在 Go 中使用接口进行灵活缓存
在 Go 中使用接口进行灵活缓存
|
2月前
|
XML 存储 JSON
在Go中使用接口:实用性与脆弱性的平衡
在Go中使用接口:实用性与脆弱性的平衡
|
2月前
|
SQL 安全 测试技术
[go 面试] 接口测试的方法与技巧
[go 面试] 接口测试的方法与技巧
|
2月前
|
存储 安全 程序员
|
2月前
|
存储 设计模式 Go
深入理解Go语言的接口
【8月更文挑战第31天】
11 0
|
2月前
|
算法 安全 测试技术
Go - 常用签名算法的基准测试
Go - 常用签名算法的基准测试
25 2
|
3月前
|
运维 监控 测试技术
Golang质量生态建设问题之接入并使用Go单元测试插件的问题如何解决
Golang质量生态建设问题之接入并使用Go单元测试插件的问题如何解决
|
2月前
|
JSON 测试技术 Go
Go 单元测试完全指南(一)- 基本测试流程
Go 单元测试完全指南(一)- 基本测试流程
14 0