121 lines
2.4 KiB
Go
121 lines
2.4 KiB
Go
package ip_tool
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"github.com/pkg/errors"
|
||
"github.com/redis/go-redis/v9"
|
||
"log"
|
||
"testing"
|
||
"time"
|
||
)
|
||
|
||
func TestHuaChenIpClient_GetIpInfo(t *testing.T) {
|
||
type fields struct {
|
||
AppCode string
|
||
Host string
|
||
}
|
||
type args struct {
|
||
ip string
|
||
}
|
||
tests := []struct {
|
||
name string
|
||
fields fields
|
||
args args
|
||
wantRes *ApiResult
|
||
wantErr bool
|
||
}{
|
||
{
|
||
name: "test1",
|
||
fields: fields{
|
||
AppCode: "",
|
||
Host: "https://c2ba.api.huachen.cn",
|
||
},
|
||
args: args{
|
||
ip: "8.138.116.112",
|
||
},
|
||
},
|
||
}
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
h := &HuaChenIpClient{
|
||
AppCode: tt.fields.AppCode,
|
||
Host: tt.fields.Host,
|
||
}
|
||
gotRes, err := h.GetIpInfo(tt.args.ip)
|
||
log.Println(gotRes, err)
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestHuaChenIpClient_GetIpInfo1(t *testing.T) {
|
||
rdb := redis.NewClient(&redis.Options{
|
||
Addr: "",
|
||
Password: "",
|
||
DB: 1,
|
||
})
|
||
|
||
// 创建IP缓存实例
|
||
ipCache := NewRedisCache(rdb)
|
||
h := &HuaChenIpClient{
|
||
AppCode: "",
|
||
Host: "https://c2ba.api.huachen.cn",
|
||
cache: ipCache,
|
||
}
|
||
gotRes, err := h.GetIpInfoFormCache(context.Background(), "8.138.116.112")
|
||
log.Println(gotRes, err)
|
||
}
|
||
|
||
type RedisCache struct {
|
||
client *redis.Client
|
||
}
|
||
|
||
func NewRedisCache(client *redis.Client) *RedisCache {
|
||
return &RedisCache{client: client}
|
||
}
|
||
|
||
func (r *RedisCache) Set(ctx context.Context, ip string, info string, ttl time.Duration) error {
|
||
if ip == "" {
|
||
return errors.New("ip不能为空")
|
||
}
|
||
|
||
return r.client.Set(ctx, ip, info, ttl).Err()
|
||
}
|
||
|
||
// Get 从Redis获取IP信息
|
||
func (r *RedisCache) Get(ctx context.Context, ip string) (*ApiResult, error) {
|
||
if ip == "" {
|
||
return nil, errors.New("ip不能为空")
|
||
}
|
||
|
||
data, err := r.client.Get(ctx, ip).Bytes()
|
||
if err != nil {
|
||
if errors.Is(err, redis.Nil) {
|
||
return nil, nil // 键不存在,返回nil而不是错误
|
||
}
|
||
return nil, fmt.Errorf("无法获取IP信息: %w", err)
|
||
}
|
||
|
||
var info ApiResult
|
||
if err = json.Unmarshal(data, &info); err != nil {
|
||
return nil, fmt.Errorf("无法解析IP信息: %w", err)
|
||
}
|
||
|
||
return &info, nil
|
||
}
|
||
|
||
// Exists 检查IP是否存在缓存中
|
||
func (r *RedisCache) Exists(ctx context.Context, ip string) (bool, error) {
|
||
if ip == "" {
|
||
return false, errors.New("ip不能为空")
|
||
}
|
||
|
||
exists, err := r.client.Exists(ctx, ip).Result()
|
||
if err != nil {
|
||
return false, fmt.Errorf("无法检查IP是否存在: %w", err)
|
||
}
|
||
|
||
return exists > 0, nil
|
||
}
|