结合 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的测试相比其他语言还是比较简洁的,这里需要注意几点:
- 测试文件以_test结尾
- 基础测试方法名要以TEST开头
运行起来,看一下:
对图中做一些说明:
// -run="none"不执行基础单元测试,bench指定基准测试方法
go test -v -run="none" -bench="Bench*"
// 最后一个BenchmarkHttpIndex-4后面测试结果表示
一共执行了11010次,每次执行耗时107392ns(~0.107ms)
结后语
文章很基础,主要是介绍了结合了gin+gorm+go-redis,并写了简单的测试,是相对基础的文章,但足以应付一些api接口了。希望对你有帮助,有问题可留言或私信。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: