hikvision/isc/artemis-hikvision.go

65 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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
}