具体计算过程,可以参考各种语言的示例代码。
使用任何API时,均需进行加密签名。以下,将以「hello」这个API做为示例。
01
/首先用一个方法来生成签名。
func MakeHMAC(nonce, path, secretKey string) string {
// Create a new HMAC by defining the hash type and the key (as byte array)
h := hmac.New(sha256.New, []byte(secretKey))
// Write Data to it
h.Write([]byte(nonce))
h.Write([]byte(path))
// Get result and encode as hexadecimal string
sha := hex.EncodeToString(h.Sum(nil))
fmt.Println("Result: " + sha)
return sha
}
02
/然后设置各Header并调用该API。
// Generate a full URL
func GetFullUrl(base, path string) string {
var buffer bytes.Buffer
buffer.WriteString(base)
buffer.WriteString(path)
return buffer.String()
}
func GetApiExample(accessKey, secretKey, basePath, nonce string) {
helloPath := "/api/v1/hello"
// Generate a signature
signHello := MakeHMAC(nonce, helloPath, secretKey)
// Set headers and call the api
client := &http.Client{}
req, _ := http.NewRequest("GET", GetFullUrl(basePath, helloPath), nil)
req.Header.Set("nonce", nonce)
req.Header.Set("accessKey", accessKey)
req.Header.Set("signature", signHello)
res, err := client.Do(req)
// Output response
if err != nil {
fmt.Printf("The HTTP request failed with error %s\n", err)
} else {
data, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(data))
}
}
03
/最后在Main方法里执行。
import "strconv"
func main() {
fmt.Println("Starting the application...")
accessKey := "Your Access Key"
secretKey := "Your Secret Key"
BasePath := "https://translate.rozetta-api.io"
millis:= time.Now().UnixNano() / 1e6
nonce := strconv.FormatInt(millis, 10)
GetApiExample(accessKey, secretKey, BasePath, nonce)
fmt.Println("Terminating the application...")
}