| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- package reply
- import (
- "encoding/json"
- "net/http"
- "github.com/go-kratos/kratos/v2/errors"
- http2 "github.com/go-kratos/kratos/v2/transport/http"
- )
- type SuccessReply struct {
- Code int32 `json:"code"`
- Message string `json:"message"`
- Data interface{} `json:"data"`
- }
- func SetContentType(w http.ResponseWriter, contentType string) {
- if contentType == "" {
- return
- }
- w.Header().Set("Content-Type", contentType)
- }
- func ErrorReturn(err error, w http.ResponseWriter, r *http.Request, h http2.HandleOptions) {
- errStatus := errors.FromError(err)
- if errStatus != nil {
- if errStatus.Reason != "" {
- fail := &SuccessReply{
- Code: errStatus.GRPCStatus().Proto().Code,
- Message: errStatus.GRPCStatus().Message(),
- }
- var obj interface{}
- json.Unmarshal([]byte(errors.Reason(err)), &obj)
- fail.Data = obj
- w.WriteHeader(400)
- if err = h.Encode(w, r, fail); err != nil {
- h.Error(w, r, err)
- }
- return
- }
- }
- h.Error(w, r, err)
- return
- }
|