How to read error from HTTP response body

吃可爱长大的小学妹 提交于 2020-01-11 12:08:00

问题


This is how error looks like, I just need "Body" when I try fmt.Println(err)

Console

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

Controller

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:


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


来源:https://stackoverflow.com/questions/55372166/how-to-read-error-from-http-response-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!