问题
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