github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_middleware_handler_response.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"net/http"
    11  
    12  	"github.com/wangyougui/gf/v2/errors/gcode"
    13  	"github.com/wangyougui/gf/v2/errors/gerror"
    14  )
    15  
    16  // DefaultHandlerResponse is the default implementation of HandlerResponse.
    17  type DefaultHandlerResponse struct {
    18  	Code    int         `json:"code"    dc:"Error code"`
    19  	Message string      `json:"message" dc:"Error message"`
    20  	Data    interface{} `json:"data"    dc:"Result data for certain request according API definition"`
    21  }
    22  
    23  // MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
    24  func MiddlewareHandlerResponse(r *Request) {
    25  	r.Middleware.Next()
    26  
    27  	// There's custom buffer content, it then exits current handler.
    28  	if r.Response.BufferLength() > 0 {
    29  		return
    30  	}
    31  
    32  	var (
    33  		msg  string
    34  		err  = r.GetError()
    35  		res  = r.GetHandlerResponse()
    36  		code = gerror.Code(err)
    37  	)
    38  	if err != nil {
    39  		if code == gcode.CodeNil {
    40  			code = gcode.CodeInternalError
    41  		}
    42  		msg = err.Error()
    43  	} else {
    44  		if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
    45  			msg = http.StatusText(r.Response.Status)
    46  			switch r.Response.Status {
    47  			case http.StatusNotFound:
    48  				code = gcode.CodeNotFound
    49  			case http.StatusForbidden:
    50  				code = gcode.CodeNotAuthorized
    51  			default:
    52  				code = gcode.CodeUnknown
    53  			}
    54  			// It creates error as it can be retrieved by other middlewares.
    55  			err = gerror.NewCode(code, msg)
    56  			r.SetError(err)
    57  		} else {
    58  			code = gcode.CodeOK
    59  		}
    60  	}
    61  
    62  	r.Response.WriteJson(DefaultHandlerResponse{
    63  		Code:    code.Code(),
    64  		Message: msg,
    65  		Data:    res,
    66  	})
    67  }