如何从HTTP响应正文读取错误

时间:2019-03-27 07:49:40

标签: json api go controller beego

这是错误的样子,尝试"Body"时我只需要fmt.Println(err)

控制台

Expected HTTP response code [200] when accessing [POST http://controller:8774/v2.1/os-keypairs], but got 409 instead
{"conflictingRequest": {"message": "Key pair 'Darkhaa test hi' already exists.", "code": 409}}

控制器

createKeyPair, err := compute.CreateKeypair(raw["keyPairName"].(string))

if err != nil {
    fmt.Println(err)
    lists["retType"] = -1
    lists["retDesc"] = err
} else {
    lists["retType"] = 0
    lists["retDesc"] = ""
    lists["retData"] = createKeyPair
}

i.Data["json"] = lists

1 个答案:

答案 0 :(得分:1)

type ErrorStruct struct {
    ConflictingRequest struct {
        Message string `json:"message"`
        Code    int    `json:"code"`
    } `json:"conflictingRequest"`
}

go func() {
    _, err := compute.CreateKeypair(raw["keyPairName"].(string))
    if err != nil {
        re := regexp.MustCompile("\\{(.*?)\\}")
        match := re.FindStringSubmatch(err.Error())
        data := ErrorStruct{}
        json.Unmarshal([]byte(match[1]), data)
        log.Printf("Message: %s", data.Message)
    }
}