定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// 1、确定struct有多少参数 type responseJson struct { httpStatus int `json:"-"` Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` } // 2、定义Option type Option func(*responseJson) // 3、每个参数都写一个方法,返回一个Option func WithCode(code int) Option { // 传入新值,存储在option中 return func(response *responseJson) { response.Code = code } } /*func WithMessage(message string) Option { return func(response *responseJson) { response.message = message } }*/ func WithHttpStatus(httpStatus int) Option { return func(response *responseJson) { response.httpStatus = httpStatus } } func WithData(data interface{}) Option { return func(response *responseJson) { response.Data = data } } func Ok(ctx *gin.Context,opts ...Option) { // 设置默认值 response := &responseJson{ httpStatus: http.StatusOK, Code: dist.RequestSuccess, Data: nil, Message: dist.CodeText(dist.RequestSuccess,lang), } // 遍历option,覆盖struct参数的值 for _,opt := range opts{ opt(response) } ctx.JSON(http.StatusOK,&responseJson{ Code: dist.RequestSuccess, Data: response.Data, Message: response.Message, }) } |
使用
1 |
response.Ok(c,WithCode(200)) |