6 Commits

Author SHA1 Message Date
yuguojian
d0d264d1e7 增加地址解析 2025-07-17 17:16:49 +08:00
lzh
aee7202752 阿里云oss 2025-07-16 15:54:18 +08:00
lzh
5f9f144ab3 阿里云oss 2025-07-16 15:51:16 +08:00
lzh
e246123ce2 阿里云oss 2025-07-16 14:56:48 +08:00
lzh
1e2d00edaf 阿里云oss 2025-07-16 14:55:59 +08:00
lzh
0c7ec61e65 阿里云oss添加删除接口 2025-07-16 14:12:11 +08:00
5 changed files with 282 additions and 78 deletions

View File

@@ -16,13 +16,13 @@ import (
type AnNaQiGpsClient struct { type AnNaQiGpsClient struct {
AppCode string AppCode string
Host string host string
} }
func NewAnNaQiGpsClient(appCode string) *AnNaQiGpsClient { func NewAnNaQiGpsClient(appCode string) *AnNaQiGpsClient {
return &AnNaQiGpsClient{ return &AnNaQiGpsClient{
AppCode: appCode, AppCode: appCode,
Host: "https://jmgeocode.market.alicloudapi.com", host: "https://jmgeocode.market.alicloudapi.com",
} }
} }
@@ -32,7 +32,7 @@ func (n *AnNaQiGpsClient) GetGpsInfo(longitude, latitude float64) (res *AddressC
location := lo + "," + la location := lo + "," + la
// 拼接URL // 拼接URL
var fullURL string var fullURL string
fullURL, err = url.JoinPath(n.Host, "geocode/regeo_query") fullURL, err = url.JoinPath(n.host, "geocode/regeo_query")
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "获取gps:%s信息失败拼接路径错误", location) return nil, errors.Wrapf(err, "获取gps:%s信息失败拼接路径错误", location)
} }
@@ -56,6 +56,9 @@ func (n *AnNaQiGpsClient) GetGpsInfo(longitude, latitude float64) (res *AddressC
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "获取gps:%s信息失败发送请求失败", location) return nil, errors.Wrapf(err, "获取gps:%s信息失败发送请求失败", location)
} }
if resp.StatusCode != http.StatusOK {
return nil, errors.New(fmt.Sprintf("获取gps:%s信息失败%+v", location, resp.Status))
}
defer func(Body io.ReadCloser) { defer func(Body io.ReadCloser) {
err = Body.Close() err = Body.Close()
if err != nil { if err != nil {
@@ -76,67 +79,67 @@ func (n *AnNaQiGpsClient) GetGpsInfo(longitude, latitude float64) (res *AddressC
return nil, errors.Wrapf(err, "获取gps:%s信息失败解析JSON响应失败%s", location, string(body)) return nil, errors.Wrapf(err, "获取gps:%s信息失败解析JSON响应失败%s", location, string(body))
} }
// 检查API返回状态 // 检查API返回状态
if apiResult.Code != 200 { if apiResult.Code == 200 {
return nil, errors.New(fmt.Sprintf("获取gps:%s信息失败%+v", location, apiResult)) if len(apiResult.Data.Regeocodes) > 0 {
return &apiResult.Data.Regeocodes[0].AddressComponent, nil
}
} }
if len(apiResult.Data.Regeocodes) > 0 {
return &apiResult.Data.Regeocodes[0].AddressComponent, nil
}
return nil, errors.New(fmt.Sprintf("获取gps:%s信息失败%+v", location, apiResult)) return nil, errors.New(fmt.Sprintf("获取gps:%s信息失败%+v", location, apiResult))
} }
type ApiResult struct { func (n *AnNaQiGpsClient) GetLocation(city, region, address string) (res *[]Geocode, err error) {
Data Data `json:"data"` values := url.Values{}
Msg string `json:"msg"` values.Set("city", city)
Success bool `json:"success"` values.Set("address", region+address)
Code int `json:"code"`
TaskNo string `json:"taskNo"`
}
type Data struct { // 创建请求
Regeocodes []Regeocode `json:"regeocodes"` var req *http.Request
} req, err = http.NewRequest(http.MethodPost, n.host+"/geocode/geo/query", bytes.NewBuffer([]byte(values.Encode())))
if err != nil {
return nil, errors.Wrapf(err, "获取经纬度失败,创建请求失败")
}
// 设置请求头
req.Header.Add("Authorization", "APPCODE "+n.AppCode)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
type Regeocode struct { // 发送请求
FormattedAddress string `json:"formatted_address"` // 创建HTTP客户端
AddressComponent AddressComponent `json:"addressComponent"` client := &http.Client{}
} client.Timeout = 5 * time.Second
var resp *http.Response
resp, err = client.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "获取经纬度失败,发送请求失败")
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New(fmt.Sprintf("获取经纬度失败,%+v", resp.Status))
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
log.Printf("关闭获取经纬度响应体失败: %+v\n", err)
}
}(resp.Body)
// 读取响应体
var body []byte
body, err = io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrapf(err, "获取经纬度失败,读取响应体失败")
}
type AddressComponent struct { // 解析JSON响应
// BusinessAreas []interface{} `json:"businessAreas"` var locationInfo LocationInfo
Country string `json:"country"` err = json.Unmarshal(body, &locationInfo)
Province string `json:"province"` if err != nil {
Citycode string `json:"citycode"` return nil, errors.Wrapf(err, "获取经纬度失败解析JSON响应失败%s", string(body))
City string `json:"city"` }
Adcode string `json:"adcode"` // 检查API返回状态
// StreetNumber StreetNumber `json:"streetNumber"` if locationInfo.Code == 200 {
// Towncode string `json:"towncode"` if len(locationInfo.Data.Geocodes) > 0 {
// District string `json:"district"` return &locationInfo.Data.Geocodes, nil
// Neighborhood Neighborhood `json:"neighborhood"` }
// Township string `json:"township"` }
// Building Building `json:"building"`
}
type BusinessArea struct { return nil, errors.New(fmt.Sprintf("获取经纬度失败,%+v", locationInfo.Msg))
Name string `json:"name"`
Location string `json:"location"`
Id string `json:"id"`
}
type StreetNumber struct {
Number string `json:"number"`
Distance string `json:"distance"`
Street string `json:"street"`
Location string `json:"location"`
Direction string `json:"direction"`
}
type Neighborhood struct {
Name interface{} `json:"name"`
Type interface{} `json:"type"`
}
type Building struct {
Name interface{} `json:"name"`
Type interface{} `json:"type"`
} }

View File

@@ -2,6 +2,7 @@ package gps_tool
import ( import (
"log" "log"
"reflect"
"testing" "testing"
) )
@@ -25,7 +26,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test1", name: "test1",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 113.419152, longitude: 113.419152,
@@ -37,7 +37,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test2", name: "test2",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 110.165223, longitude: 110.165223,
@@ -48,7 +47,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test2", name: "test2",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 115.928973, longitude: 115.928973,
@@ -60,7 +58,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test3", name: "test3",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 107.397284, longitude: 107.397284,
@@ -72,7 +69,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test4", name: "test4",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 115.929015, longitude: 115.929015,
@@ -84,7 +80,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test5", name: "test5",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 115.929100, longitude: 115.929100,
@@ -96,7 +91,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test6", name: "test6",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 126.587051, longitude: 126.587051,
@@ -108,7 +102,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test7", name: "test7",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 126.595051, longitude: 126.595051,
@@ -120,7 +113,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test8", name: "test8",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 125.342693, longitude: 125.342693,
@@ -132,7 +124,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test9", name: "test9",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 112.485550, longitude: 112.485550,
@@ -144,7 +135,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test10", name: "test10",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 115.928821, longitude: 115.928821,
@@ -156,7 +146,6 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
name: "test11", name: "test11",
fields: fields{ fields: fields{
AppCode: "", AppCode: "",
Host: "https://jmgeocode.market.alicloudapi.com",
}, },
args: args{ args: args{
longitude: 115.928821, longitude: 115.928821,
@@ -166,12 +155,55 @@ func TestAnNaQiGpsClient_GetGpsInfo(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
n := &AnNaQiGpsClient{ n := NewAnNaQiGpsClient(tt.fields.AppCode)
AppCode: tt.fields.AppCode,
Host: tt.fields.Host,
}
gotRes, err := n.GetGpsInfo(tt.args.longitude, tt.args.latitude) gotRes, err := n.GetGpsInfo(tt.args.longitude, tt.args.latitude)
log.Println(gotRes, err) log.Println(gotRes, err)
}) })
} }
} }
func TestAnNaQiGpsClient_GetLocation(t *testing.T) {
type fields struct {
AppCode string
Host string
}
type args struct {
city string
region string
address string
}
tests := []struct {
name string
fields fields
args args
wantRes *[]Geocode
wantErr bool
}{
{
name: "奥园城市天地",
fields: fields{
AppCode: "",
},
args: args{
city: "广州",
region: "番禺",
address: "奥园城市天地9区2栋",
},
wantRes: nil,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
n := NewAnNaQiGpsClient(tt.fields.AppCode)
gotRes, err := n.GetLocation(tt.args.city, tt.args.region, tt.args.address)
if (err != nil) != tt.wantErr {
t.Errorf("GetLocation() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotRes, tt.wantRes) {
t.Errorf("GetLocation() gotRes = %v, want %v", gotRes, tt.wantRes)
}
})
}
}

81
gps_tool/response.go Normal file
View File

@@ -0,0 +1,81 @@
package gps_tool
type ApiResult struct {
Data Data `json:"data"`
Msg string `json:"msg"`
Success bool `json:"success"`
Code int `json:"code"`
TaskNo string `json:"taskNo"`
}
type Data struct {
Regeocodes []Regeocode `json:"regeocodes"`
}
type Regeocode struct {
FormattedAddress string `json:"formatted_address"`
AddressComponent AddressComponent `json:"addressComponent"`
}
type AddressComponent struct {
// BusinessAreas []interface{} `json:"businessAreas"`
Country string `json:"country"`
Province string `json:"province"`
Citycode string `json:"citycode"`
City string `json:"city"`
Adcode string `json:"adcode"`
// StreetNumber StreetNumber `json:"streetNumber"`
// Towncode string `json:"towncode"`
// District string `json:"district"`
// Neighborhood Neighborhood `json:"neighborhood"`
// Township string `json:"township"`
// Building Building `json:"building"`
}
type BusinessArea struct {
Name string `json:"name"`
Location string `json:"location"`
Id string `json:"id"`
}
type StreetNumber struct {
Number string `json:"number"`
Distance string `json:"distance"`
Street string `json:"street"`
Location string `json:"location"`
Direction string `json:"direction"`
}
type Neighborhood struct {
Name interface{} `json:"name"`
Type interface{} `json:"type"`
}
type Building struct {
Name interface{} `json:"name"`
Type interface{} `json:"type"`
}
type LocationInfo struct {
Data LocationDatum `json:"data"`
Msg string `json:"msg"`
Success bool `json:"success"`
Code int `json:"code"`
TaskNo string `json:"taskNo"`
}
type LocationDatum struct {
Count int `json:"count"`
Geocodes []Geocode `json:"geocodes"`
}
type Geocode struct {
Country string `json:"country"`
FormattedAddress string `json:"formatted_address"`
City string `json:"city"`
Adcode string `json:"adcode"`
Level string `json:"level"`
Province string `json:"province"`
Citycode string `json:"citycode"`
District string `json:"district"`
Location string `json:"location"`
}

View File

@@ -22,6 +22,7 @@ type ALiYunOSSClient struct {
ossClient *oss.Client ossClient *oss.Client
} }
// NewAliYunOSS 创建阿里云OSS客户端
func (c *ALiYunOSSClient) NewAliYunOSS() (err error) { func (c *ALiYunOSSClient) NewAliYunOSS() (err error) {
if c.AccessKeyID == "" || c.AccessKeySecret == "" { if c.AccessKeyID == "" || c.AccessKeySecret == "" {
return errors.New("请配置 oss accessKeyID accessKeySecret") return errors.New("请配置 oss accessKeyID accessKeySecret")
@@ -35,14 +36,14 @@ func (c *ALiYunOSSClient) NewAliYunOSS() (err error) {
return nil return nil
} }
func (c *ALiYunOSSClient) GetSignUrl(bucket string, key string, expires time.Duration) (result *oss.PresignResult, err error) { // BuildPutSignUrl 获取上传签名
func (c *ALiYunOSSClient) BuildPutSignUrl(bucket string, key string, expires time.Duration) (result *oss.PresignResult, err error) {
// 生成PutObject的预签名URL // 生成PutObject的预签名URL
result, err = c.ossClient.Presign( result, err = c.ossClient.Presign(
context.Background(), context.Background(),
&oss.PutObjectRequest{ &oss.PutObjectRequest{
Bucket: oss.Ptr(bucket), Bucket: oss.Ptr(bucket),
Key: oss.Ptr(key), Key: oss.Ptr(key),
//ContentType: oss.Ptr("application/octet-stream"),
}, },
oss.PresignExpires(expires), oss.PresignExpires(expires),
) )
@@ -52,6 +53,33 @@ func (c *ALiYunOSSClient) GetSignUrl(bucket string, key string, expires time.Dur
return return
} }
// BuildPutSignUrlByPutObjectRequest 根据PutObjectRequest生成PutObject的预签名URL
func (c *ALiYunOSSClient) BuildPutSignUrlByPutObjectRequest(req *oss.PutObjectRequest, expires time.Duration) (result *oss.PresignResult, err error) {
// 生成PutObject的预签名URL
result, err = c.ossClient.Presign(
context.Background(),
req,
oss.PresignExpires(expires),
)
if err != nil {
return nil, err
}
return
}
// BuildSignUrlByGetObjectRequest 根据GetObjectRequest生成GetObject的预签名URL
func (c *ALiYunOSSClient) BuildSignUrlByGetObjectRequest(req *oss.GetObjectRequest) (result *oss.PresignResult, err error) {
// 生成PutObject的预签名URL
result, err = c.ossClient.Presign(
context.Background(),
req,
)
if err != nil {
return nil, err
}
return
}
// PutForLocalFile 上传本地文件 // PutForLocalFile 上传本地文件
func (c *ALiYunOSSClient) PutForLocalFile(bucket, key, path string) (result *oss.PutObjectResult, err error) { func (c *ALiYunOSSClient) PutForLocalFile(bucket, key, path string) (result *oss.PutObjectResult, err error) {
// 创建上传对象的请求 // 创建上传对象的请求
@@ -145,3 +173,18 @@ func (c *ALiYunOSSClient) GetObjectToImage(bucket string, key string) (img image
} }
return img, nil return img, nil
} }
// DelObject 删除对象
func (c *ALiYunOSSClient) DelObject(bucket string, key string) (result *oss.DeleteObjectResult, err error) {
// 创建删除对象的请求
request := &oss.DeleteObjectRequest{
Bucket: oss.Ptr(bucket), // 存储空间名称
Key: oss.Ptr(key), // 对象名称
}
// 执行删除对象的操作并处理结果
result, err = c.ossClient.DeleteObject(context.TODO(), request)
if err != nil {
return nil, err
}
return result, err
}

View File

@@ -1,6 +1,7 @@
package oss_tool package oss_tool
import ( import (
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"os" "os"
"testing" "testing"
) )
@@ -24,12 +25,28 @@ func TestALiYunOSSClient_NewAliYunOSS(t *testing.T) {
t.Log(client.ossClient) t.Log(client.ossClient)
} }
func TestALiYunOSSClient_GetSignUrl(t *testing.T) { func TestALiYunOSSClient_BuildPutSignUrl(t *testing.T) {
err := client.NewAliYunOSS() err := client.NewAliYunOSS()
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
sign, err := client.GetSignUrl("", "test/upload/bizhi1.jpg", 0) sign, err := client.BuildPutSignUrl("", "test/upload/bizhi1.jpg", 0)
if err != nil {
t.Error(err)
}
t.Log(sign)
}
func TestALiYunOSSClient_BuildPutSignUrlByPutObjectRequest(t *testing.T) {
err := client.NewAliYunOSS()
if err != nil {
t.Error(err)
}
req := &oss.PutObjectRequest{}
req.Bucket = oss.Ptr("")
req.Key = oss.Ptr("test/upload/bizhi2.jpg")
req.ContentType = oss.Ptr("application/octet-stream")
sign, err := client.BuildPutSignUrlByPutObjectRequest(req, 0)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@@ -41,7 +58,22 @@ func TestALiYunOSSClient_PutForLocalFile(t *testing.T) {
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
result, err := client.PutForLocalFile("", "test/upload/bizhi2.jpg", "C:\\Users\\Administrator\\Desktop\\壁纸1.jpg") result, err := client.PutForLocalFile("ssgfdown", "test/upload/bizhi2.jpg", "")
if err != nil {
t.Error(err)
}
t.Log(result)
}
func TestALiYunOSSClient_BuildSignUrlByGetObjectRequest(t *testing.T) {
err := client.NewAliYunOSS()
if err != nil {
t.Error(err)
}
req := &oss.GetObjectRequest{}
req.Bucket = oss.Ptr("ssgfdown")
req.Key = oss.Ptr("test/upload/bizhi2.jpg")
result, err := client.BuildSignUrlByGetObjectRequest(req)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@@ -73,3 +105,16 @@ func TestALiYunOSSClient_GetObjectToImage(t *testing.T) {
t.Log(img) t.Log(img)
} }
} }
func TestALiYunOSSClient_DelObject(t *testing.T) {
err := client.NewAliYunOSS()
if err != nil {
t.Error(err)
}
res, err := client.DelObject("", "test/upload/bizhi2.jpg")
if err != nil {
t.Error(err)
} else {
t.Log(res)
}
}