Go接入指南

更新时间:

操作步骤

步骤一:安装依赖

module demo

go 1.21.10

require github.com/google/uuid v1.6.0 // indirect

步骤二:增加Client定义

增加 client.go,按需修改 package 名称

package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/google/uuid"
)

type Client struct {
	endpoint  string
	appKey    string
	appSecret string
}

func NewClient(endpoint string, appKey string, appSecret string) *Client {
	return &Client{endpoint: endpoint, appKey: appKey, appSecret: appSecret}
}

func (c *Client) Invoke(path string, params map[string]interface{}, headers map[string]string) (*http.Response, error) {
	url := fmt.Sprintf("https://%s%s", c.endpoint, path)

	// Convert the data to JSON
	jsonData, err := json.Marshal(params)
	if err != nil {
		return nil, fmt.Errorf("marshal params with err: %w", err)
	}

	// Set up the HTTP client
	client := &http.Client{}

	// Create the request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, fmt.Errorf("create request with err: %w", err)
	}

	// Set headers
	genHeaders := c.generateHeader("POST", path, headers)
	req.Header = genHeaders

	// Make the request
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("request with err: %w", err)
	}
	return resp, nil
}

func (c *Client) generateHeader(httpMethod string, path string, headers map[string]string) http.Header {
	timestamp := time.Now().UnixNano() / int64(time.Millisecond)
	dateStr := time.Now().UTC().Format("Mon, 02 Jan 2006 15:04:05 MST") + "+00:00"
	uuidStr := uuid.New().String()
	jsonHeader := "application/json; charset=utf-8"

	h := make(http.Header)
	h.Set("Date", dateStr)
	h.Set("x-ca-key", c.appKey)
	h.Set("x-ca-timestamp", strconv.FormatInt(timestamp, 10))
	h.Set("x-ca-nonce", uuidStr)
	h.Set("x-ca-signature-method", "HmacSHA256")
	h.Set("x-ca-signature-headers", "x-ca-timestamp,x-ca-key,x-ca-nonce,x-ca-signature-method")
	h.Set("Content-Type", jsonHeader)
	h.Set("Accept", jsonHeader)

	if len(headers) > 0 {
		for k, v := range headers {
			h.Set(k, v)
		}
	}

	bodyMd5Str := ""

	var buf bytes.Buffer
	fmt.Fprintln(&buf, httpMethod)
	fmt.Fprintln(&buf, jsonHeader)
	fmt.Fprintln(&buf, bodyMd5Str)
	fmt.Fprintln(&buf, jsonHeader)
	fmt.Fprintln(&buf, dateStr)
	fmt.Fprintln(&buf, "x-ca-key:"+c.appKey)
	fmt.Fprintln(&buf, "x-ca-nonce:"+uuidStr)
	fmt.Fprintln(&buf, "x-ca-signature-method:HmacSHA256")
	fmt.Fprintf(&buf, "x-ca-timestamp:%d\n", timestamp)
	fmt.Fprint(&buf, path)

	mac := hmac.New(sha256.New, []byte(c.appSecret))
	mac.Write(buf.Bytes())
	h.Set("x-ca-signature", base64.StdEncoding.EncodeToString(mac.Sum(nil)))

	return h
}

步骤三:填写调用AK/SK、调用路径、调用参数

package main

import (
	"fmt"
	"io"
)

func main() {
	client := Client{
		endpoint:  "openai.edu-aliyun.com",
		appKey:    "应用AK",
		appSecret: "应用SK",
	}

        # 调用路径,具体参见 API
        api_path = "/scc/调用路径"

        # 调用参数
        params = map[string]interface{}{}
        params['参数名称'] = '参数值'

        # 请求头
        headers = map[string]string{}

	resp, err := client.Invoke(apiPath, data, headers)
	if err != nil {
		fmt.Printf("invoke api failed: %v\n", err)
		return
	}

	// Read the response body
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	// Print the response
	fmt.Printf("get body: %s", string(body))
}