结合 gin+gorm+go-Redis 写一个基础 API(下篇)

前两篇我们已经完成了 gin+gorm 部分,今天我们来补充 go-Redis,并进行测试。

整合 go-Redis#

我们把 Redis 相关也放在 model 下面,使用的是常见的 go-redis:

// redis.go
package model

import (
    "fmt"

    "github.com/spf13/viper"
    "github.com/go-redis/redis"
)

var RedisClient *redis.Client

func RedisInit() {
    RedisClient = redis.NewClient(&redis.Options{
        Addr:     fmt.Sprintf("%s:%s", viper.GetString("redis.host"), viper.GetString("redis.port")),
        Password: viper.GetString("redis.auth"),
        DB:       0,
    })

    _, err := RedisClient.Ping().Result()
    if err != nil {
        panic("redis ping error")
    }
}

然后在连接 Mysql 的前面加入初始化 redis 连接的操作即可。

    // redis 初始化
    model.RedisInit()

你可以做一些简单操作,或者在 redis.go 做一些常用方法的封装,比较简单,就不赘述了,更多 go-redis 操作可见:

测试#

新建测试目录 test,建立三个文件:

// index.go
package test

import (
    "net/http"
    "io/ioutil"
)

func Sum(a int, b int) int {
    return a+b
}

func HttpIndex() []byte {
    resp, err := http.Get("http://127.0.0.1:8080/")
    if err != nil && resp.StatusCode != 200 {
        panic(err)
    }
    //关闭连接
    defer resp.Body.Close()
    //读取报文中所有内容
    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        panic(err)
    }
    //输出内容
    return body
}
// index_test.go
package test

import (
    "testing"
    "encoding/json"

    "local.com/sai0556/gin-frame/controller"
)

func TestSum(t *testing.T)  {
    ret := Sum(2, 7)
    if ret != 9 {
        t.Error("Expected 9 ~wow~")
    }
}

func TestHttpIndex(t *testing.T)  {
    data := HttpIndex()

    target := controller.Response{}
    // json转换
    if err := json.Unmarshal(data, &target); err != nil {
        t.Error(target)
    }

    ret := controller.Response{0, "success", nil}

    if target != ret {
        t.Error("json error")
    }
}
// index_bench_test.go
package test

import (
    "testing"
)

func BenchmarkSum(b *testing.B)  {
    for i := 0; i < b.N; i++ { 
        Sum(2, 7)
    }
}

func BenchmarkHttpIndex(b *testing.B)  {

    for i := 0; i < b.N; i++ { 
        HttpIndex()
    }
}

私以为 go 的测试相比其他语言还是比较简洁的,这里需要注意几点:

  1. 测试文件以_test 结尾
  2. 基础测试方法名要以 TEST 开头

运行起来,看一下:

测试结果

对图中做一些说明:

// -run="none"不执行基础单元测试,bench指定基准测试方法
go test -v -run="none" -bench="Bench*"

// 最后一个BenchmarkHttpIndex-4后面测试结果表示
一共执行了11010次,每次执行耗时107392ns(~0.107ms)

test 标准库


结后语#

文章很基础,主要是介绍了结合了 gin+gorm+go-redis,并写了简单的测试,是相对基础的文章,但足以应付一些 api 接口了。希望对你有帮助,有问题可留言或私信。

点击查看项目 DEMO

go
本作品采用《CC 协议》,转载必须注明作者和本文链接