65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
// Package 海康
|
||
package isc
|
||
|
||
import (
|
||
"crypto/hmac"
|
||
"crypto/sha256"
|
||
"crypto/tls"
|
||
"encoding/base64"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
func artemisHmacSha256(message string, secret string) string {
|
||
key := []byte(secret)
|
||
h := hmac.New(sha256.New, key)
|
||
h.Write([]byte(message))
|
||
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||
}
|
||
|
||
// 海康post请求,不做错误记录
|
||
func artemisPOST(uri string, body interface{}) (*[]byte, error) {
|
||
url := fmt.Sprintf(`%s/artemis%s`, conf.Host, uri)
|
||
reqbody, _ := json.Marshal(body)
|
||
req, err := http.NewRequest("POST", url, strings.NewReader(string(reqbody)))
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
str := fmt.Sprintf("POST\n*/*\napplication/json\nx-ca-key:%s\n/artemis%s", conf.AppKey, uri)
|
||
signature := artemisHmacSha256(str, conf.AppSecret)
|
||
|
||
req.Header.Add("Accept", "*/*")
|
||
req.Header.Add("Content-Type", "application/json")
|
||
req.Header.Add("X-Ca-Key", conf.AppKey)
|
||
req.Header.Add("X-Ca-Signature", signature)
|
||
req.Header.Add("X-Ca-Signature-Headers", "x-ca-key")
|
||
|
||
tr := &http.Transport{
|
||
TLSClientConfig: &tls.Config{
|
||
InsecureSkipVerify: true,
|
||
},
|
||
}
|
||
client := &http.Client{Transport: tr, Timeout: 10 * time.Second}
|
||
resp, err := client.Do(req)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
if resp.StatusCode != 200 {
|
||
errmsg := fmt.Sprintf("http status code: %d", resp.StatusCode)
|
||
return nil, errors.New(errmsg)
|
||
}
|
||
|
||
defer resp.Body.Close()
|
||
respBody, err := io.ReadAll(resp.Body)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return &respBody, nil
|
||
}
|