免费解析素材网站,百度搜索推广优化师工作内容,企业网站如何seo,wordpress win 伪静态先自定义结构体的赋值以及到出 在 Go 语言中#xff0c;json:errorMsg 是一个 struct tag#xff0c;用于定义结构体字段在被序列化成 JSON 格式时的名称。如果你在定义结构体字段时添加了这个 tag#xff0c;那么在将结构体实例序列化为 JSON 格式时#xff0…先自定义结构体的赋值以及到出 在 Go 语言中json:errorMsg 是一个 struct tag用于定义结构体字段在被序列化成 JSON 格式时的名称。如果你在定义结构体字段时添加了这个 tag那么在将结构体实例序列化为 JSON 格式时该字段将以 “errorMsg” 作为键名而不添加这个 tag则默认会使用字段名作为键名。
举个例子假设有以下结构体定义
type Response struct {ErrorCode string json:errorCodeErrorMsg string json:errorMsgData interface{} json:data
}如果你创建了一个 Response 实例并将其序列化成 JSON 格式结果可能如下
{errorCode: 1001,errorMsg: Something went wrong,data: {...}
}可以看到由于添加了 json:errorMsg tagErrorMsg 字段被序列化为 JSON 时的键名为 “errorMsg”。
package APItype ApiResponseObject struct {ErrorCode string json:errorCodeErrorMsg string json:errorMsgData interface{} json:data
}func (response *ApiResponseObject) GetErrorCode() string {return response.ErrorCode
}func (response *ApiResponseObject) SetErrorCode(errorCode string) {response.ErrorCode errorCode
}func (response *ApiResponseObject) GetErrorMsg() string {return response.ErrorMsg
}func (response *ApiResponseObject) SetErrorMsg(errorMsg string) {response.ErrorMsg errorMsg
}func (response *ApiResponseObject) GetData() interface{} {return response.Data
}func (response *ApiResponseObject) SetData(data interface{}) {response.Data data
}
集合导出方法
package servicesimport API awesomeProject4/commonfunc ReponseJSON(errorCode string, errorMsg string, resData interface{}) API.ApiResponseObject {apiResponseObject : API.ApiResponseObject{}apiResponseObject.SetData(resData)apiResponseObject.SetErrorMsg(errorMsg)apiResponseObject.SetErrorCode(errorCode)return apiResponseObject
}
使用如果不引如 json:键名会到出ctx.json输出为空
ctx.JSON(http.StatusOK, ReponseJSON(API.SUCCESS.GetCode(), API.SUCCESS.GetName(), user))