【问题标题】:multiple response in single array in golanggolang中单个数组中的多个响应
【发布时间】:2021-05-13 23:11:11
【问题描述】:

我是 golang 的新手。我想得到我的回应作为多个结果。我做了一些方法,但我需要改变那个方法

impartErrl := ph.profileService.ValidateSchema(gojsonschema.NewStringLoader(string(b)))
        if impartErrl != nil {
            ctx.JSON(http.StatusBadRequest, impart.ErrorResponse(impartErrl))
            return
        }

func (ps *profileService) ValidateSchema(document gojsonschema.JSONLoader) (errors []impart.Error) {
    result, err := gojsonschema.Validate(ps.schemaValidator, document)
    if err != nil {
        ps.SugaredLogger.Error(err.Error())
        return impart.ErrorResponse(
            impart.NewError(impart.ErrBadRequest, "unable to validate schema"),
        )
    }

    if result.Valid() {
        return nil
    }
    // msg := fmt.Sprintf("%v validations errors.\n", len(result.Errors()))
    msg := "validations errors"
    for i, desc := range result.Errors() {
        msg += fmt.Sprintf("%v: %s\n", i, desc)
        er := impart.NewError(impart.ErrValidationError, fmt.Sprintf("%s ", desc), impart.ErrorKey(desc.Field()))
        errors = append(errors, er)
    }
    return errors
}

func NewError(err error, msg string, args ...interface{}) Error {
    key := GetErrorKey(args...)
    return impartError{
        err: err,
        msg: msg,
        key: key,
    }
}

func ErrorResponse(err interface{}) []Error {
    var errorResponse []Error
    switch err.(type) {
    case Error:
        errorResponse = []Error{err.(Error)}
    case []Error:
        errorResponse = err.([]Error)
    default:
        errorResponse = []Error{
            NewError(ErrUnknown, fmt.Sprintf("%v", err)),
        }
    }
    return errorResponse
}

type Error interface {
    error
    HttpStatus() int
    ToJson() string
    Err() error
    Msg() string
}

现在我得到的输出为

[
    {
        "error": "validation error",
        "msg": "email: Does not match format 'email' ",
        "key": "email"
    },
    {
        "error": "validation error",
        "msg": "screenName: String length must be greater than or equal to 4 ",
        "key": "screenName"
    }
]

但我需要我的回复

{
     0 :{
            "error": "validation error",
            "msg": "email: Does not match format 'email' ",
            "key": "email"
        },
    1 : {
        "error": "unable to complete the request",
        "msg": "invalid screen name, must be alphanumeric characters only",
        "key": "screen_name"
    }

}

我怎样才能得到这些类型的响应。 ?因为在 ios 应用程序中解析响应 [] 时显示错误。所以我需要改变输出。

请帮帮我。

【问题讨论】:

  • 所以ErrorResponse 应该返回map[int32]Error 而不是[]Error

标签: api go response go-gin


【解决方案1】:

ErrorResponse 函数应该返回 map[int]Error 而不是 []Error。例如:

func ErrorResponse(err interface{}) map[int]Error {
    errorResponse := map[int]Error{}
    switch e := err.(type) {
    case Error:
        errorResponse[0] = e
    case []Error:
        for i, k := range e {
            errorResponse[i] = k
        }
    default:
        errorResponse[0] = NewError(ErrUnknown, fmt.Sprintf("%v", err))
    }
    return errorResponse
}

【讨论】:

  • 我会检查两件事:1)encoding/json 在编组之前根据其键对地图进行排序,如果没有,则 2)出现不自然排序顺序的键不会中断“iOS 应用程序”。我之所以提到这一点,是因为在 Go 中,地图遍历不提供任何关于访问其键的顺序的保证。
  • @Matteo 使用这个我得到了所需的输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2016-08-20
  • 2020-01-14
  • 1970-01-01
  • 2012-08-04
相关资源
最近更新 更多