Merge pull request #1 from RXDA/main

Support go module and fix some error handling
This commit is contained in:
承诺一时的华丽
2022-05-14 21:04:42 +08:00
committed by GitHub
3 changed files with 41 additions and 41 deletions

5
go.mod Normal file
View File

@@ -0,0 +1,5 @@
module github.com/zxbit2011/hikvisionOpenAPIGo
go 1.16
require github.com/gofrs/uuid v4.2.0+incompatible

2
go.sum Normal file
View File

@@ -0,0 +1,2 @@
github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=
github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=

75
sdk.go
View File

@@ -10,10 +10,11 @@ import (
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
uuid "github.com/satori/go.uuid" "github.com/gofrs/uuid"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"sort" "sort"
"strconv"
"strings" "strings"
"time" "time"
) )
@@ -48,17 +49,21 @@ type Data struct {
// @return 请求结果 参数类型 // @return 请求结果 参数类型
func (hk HKConfig) HttpPost(url string, body map[string]string, timeout int) (result Result, err error) { func (hk HKConfig) HttpPost(url string, body map[string]string, timeout int) (result Result, err error) {
var header = make(map[string]string) var header = make(map[string]string)
bodyJson := MustJsonString(body) bodyJson, err := json.Marshal(body)
hk.initRequest(header, url, bodyJson, true) if err != nil {
return result, err
}
err = hk.initRequest(header, url, string(bodyJson), true)
if err != nil {
return Result{}, err
}
var sb []string var sb []string
if hk.IsHttps { if hk.IsHttps {
sb = append(sb, "https://") sb = append(sb, "https://")
} else { } else {
sb = append(sb, "http://") sb = append(sb, "http://")
} }
sb = append(sb, hk.Ip) sb = append(sb, fmt.Sprintf("%s:%d", hk.Ip, hk.Port))
sb = append(sb, ":")
sb = append(sb, fmt.Sprintf("%d", hk.Port))
sb = append(sb, url) sb = append(sb, url)
client := &http.Client{} client := &http.Client{}
@@ -72,7 +77,7 @@ func (hk HKConfig) HttpPost(url string, body map[string]string, timeout int) (re
} }
client.Transport = tr client.Transport = tr
} }
req, err := http.NewRequest("POST", strings.Join(sb, ""), bytes.NewReader([]byte(bodyJson))) req, err := http.NewRequest("POST", strings.Join(sb, ""), bytes.NewReader(bodyJson))
if err != nil { if err != nil {
return return
} }
@@ -98,7 +103,7 @@ func (hk HKConfig) HttpPost(url string, body map[string]string, timeout int) (re
err = json.Unmarshal(resBody, &result) err = json.Unmarshal(resBody, &result)
} else if resp.StatusCode == http.StatusFound || resp.StatusCode == http.StatusMovedPermanently { } else if resp.StatusCode == http.StatusFound || resp.StatusCode == http.StatusMovedPermanently {
reqUrl := resp.Header.Get("Location") reqUrl := resp.Header.Get("Location")
panic(fmt.Errorf("HttpPost Response StatusCode%dLocation%s", resp.StatusCode, reqUrl)) err = fmt.Errorf("HttpPost Response StatusCode%dLocation%s", resp.StatusCode, reqUrl)
} else { } else {
err = fmt.Errorf("HttpPost Response StatusCode%d", resp.StatusCode) err = fmt.Errorf("HttpPost Response StatusCode%d", resp.StatusCode)
} }
@@ -106,14 +111,21 @@ func (hk HKConfig) HttpPost(url string, body map[string]string, timeout int) (re
} }
// initRequest 初始化请求头 // initRequest 初始化请求头
func (hk HKConfig) initRequest(header map[string]string, url, body string, isPost bool) { func (hk HKConfig) initRequest(header map[string]string, url, body string, isPost bool) error {
header["Accept"] = "application/json" header["Accept"] = "application/json"
header["Content-Type"] = "application/json" header["Content-Type"] = "application/json"
if isPost { if isPost {
header["content-md5"] = computeContentMd5(body) var err error
header["content-md5"], err = computeContentMd5(body)
if err != nil {
return err
}
}
header["x-ca-timestamp"] = strconv.FormatInt(time.Now().UnixMilli(), 10)
uid, err := uuid.NewV4()
if err != nil {
return err
} }
header["x-ca-timestamp"] = MustString(time.Now().UnixNano() / 1e6)
uid, _ := uuid.NewV4()
header["x-ca-nonce"] = uid.String() header["x-ca-nonce"] = uid.String()
header["x-ca-key"] = hk.AppKey header["x-ca-key"] = hk.AppKey
@@ -125,15 +137,21 @@ func (hk HKConfig) initRequest(header map[string]string, url, body string, isPos
} }
signedStr, err := computeForHMACSHA256(strToSign, hk.Secret) signedStr, err := computeForHMACSHA256(strToSign, hk.Secret)
if err != nil { if err != nil {
println(err.Error()) return err
return
} }
header["x-ca-signature"] = signedStr header["x-ca-signature"] = signedStr
return nil
} }
// computeContentMd5 计算content-md5 // computeContentMd5 计算content-md5
func computeContentMd5(body string) string { func computeContentMd5(body string) (string, error) {
return base64.StdEncoding.EncodeToString([]byte(Md5(body))) h := md5.New()
_, err := h.Write([]byte(body))
if err != nil {
return "", err
}
md5Str := hex.EncodeToString(h.Sum(nil))
return base64.StdEncoding.EncodeToString([]byte(md5Str)), nil
} }
// computeForHMACSHA256 计算HMACSHA265 // computeForHMACSHA256 计算HMACSHA265
@@ -206,28 +224,3 @@ func buildSignHeader(header map[string]string) string {
header["x-ca-signature-headers"] = strings.Join(sbSignHeader, "") header["x-ca-signature-headers"] = strings.Join(sbSignHeader, "")
return strings.Join(sb, "") return strings.Join(sb, "")
} }
func MustJson(i interface{}) []byte {
if d, err := json.Marshal(i); err == nil {
return d
} else {
panic(err)
}
}
func MustJsonString(i interface{}) string {
return string(MustJson(i))
}
func MustString(value interface{}) string {
if value == nil {
return ""
}
return fmt.Sprintf("%v", value)
}
func Md5(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}