package basic // StatusResponse 公司自定义状态码 type StatusResponse struct { Code int Message string } var ( CodeOK = &StatusResponse{200, "success"} // 成功 CodeApiErr = &StatusResponse{500, "api error"} // api 错误 CodeSaveErr = &StatusResponse{501, "fail to save"} // 储存错误 CodeServiceErr = &StatusResponse{510, "server logic error"} // server logic 错误 CodeUnAuth = &StatusResponse{401, "unauthorized"} // 未授权 CodeUpdateErr = &StatusResponse{5000, "update database error"} // update database logic 错误 CodeDupGuestErr = &StatusResponse{5001, "the user is already a guest user and does not need to apply again"} // 用户已经是guest用户不需要重复申请 错误 CodeRequestParamsErr = &StatusResponse{5002, "invalid request param"} // api参数校验 错误 CodeDbRecordNotFoundErr = &StatusResponse{5003, "db record not found"} ) type Response struct { Code int `json:"code"` Message string `json:"msg"` Data interface{} `json:"data"` } // Set 设置Response的Code和Message值 func (resp *Response) Set(Code int, Message string) *Response { return &Response{ Code: Code, Message: Message, } } // Set 设置整个Response func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response { return &Response{ Code: Code, Message: Message, Data: Data, } } // SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 func (resp *Response) SetStatus(sr *StatusResponse, data ...interface{}) *Response { newResp := &Response{ Code: sr.Code, Message: sr.Message, } if len(data) == 1 { newResp.Data = data[0] } return newResp } // SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 func (resp *Response) SetStatusWithMessage(sr *StatusResponse, msg string, data ...interface{}) *Response { newResp := &Response{ Code: sr.Code, Message: msg, } if len(data) == 1 { newResp.Data = data[0] } return newResp }