You need to enable JavaScript to run this app.
导航
OpenAPI使用示例
最近更新时间:2024.08.20 17:45:30首次发布时间:2023.12.01 20:15:46

本文介绍了应用性能监控全链路版(APMPlus)提供的各语言版本的Demo示例,帮助您快速调用OpenAPI。

前提条件

您需要使用签名SDK中的签名方法。各语言的SDK地址,请参见V1版本

注意

示例代码强依赖于签名SDK,不能使用通过签名机制构建的Authorization。

示例代码

package main

import (
    "bytes"
    "context"
    "fmt"
    "io"
    "net/http"
    "time"

    volc "github.com/volcengine/volc-sdk-golang/base"
)

const (
    Host        = "https://open.volcengineapi.com"
    ServiceName = "apmplus_openapi"
    Region      = "cn-beijing"
    AK          = "xx"
    SK          = "xx=="
)

func main() {
    // 1. 初始化方法信息
    var (
        action  = "GetAppAlarmRuleList" // 接口名
        version = "2022-10-12"          // 接口版本
        appID   = "123456"              // 应用id
    )
    ctx := context.Background()
    // 2. 构造请求体
    req := buildRequest(ctx, action, version, appID)
    // 3. 发起请求
    cli := &http.Client{Timeout: time.Second * 5}
    resp, err := cli.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    data, _ := io.ReadAll(resp.Body)
    fmt.Println(string(data))
}

// buildRequest
func buildRequest(ctx context.Context, action, version, appID string) *http.Request {
    payload := buildRequestJsonBody()
    body := bytes.NewBuffer([]byte(payload))

    req, _ := http.NewRequest("POST", Host, body)
    q := req.URL.Query()
    q.Add("Action", action)
    q.Add("Version", version)
    req.URL.RawQuery = q.Encode()
    req.Header.Set("x-app-ids", appID)
    req.Header.Set("content-type", "application/json")
    // sign签名
    c := volc.Credentials{
        AccessKeyID:     AK,
        SecretAccessKey: SK,
        Service:         ServiceName,
        Region:          Region,
    }
    req = c.Sign(req)
    return req
}

// buildRequsetBody 当前接口的请求 body,json string 格式
func buildRequestJsonBody() string {
    return `{
        "monitor_types":[
            "crash"
        ],
        "query_key":"测试报警",
        "status":[
        ],
        "page_no":1,
        "page_size":1
    }`
}

调用接口时,请修改示例代码为对应接口的Action、AppID、AK、SK、Service、Region。