You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.6 KiB
67 lines
1.6 KiB
package http
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/go-kratos/kratos/v2/errors"
|
|
"github.com/go-kratos/kratos/v2/transport/http"
|
|
stdhttp "net/http"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
baseContentType = "application"
|
|
)
|
|
|
|
type Response struct {
|
|
Code int `json:"code" form:"code"`
|
|
Data interface{} `json:"data" form:"data"`
|
|
Reason string `json:"reason" form:"reason"`
|
|
Message string `json:"message" form:"message"`
|
|
}
|
|
|
|
func ResponseEncoder(w stdhttp.ResponseWriter, r *stdhttp.Request, v interface{}) error {
|
|
if v == nil {
|
|
return nil
|
|
}
|
|
|
|
codec, _ := http.CodecForRequest(r, "Accept")
|
|
data, err := codec.Marshal(v)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
application := strings.Join([]string{baseContentType, codec.Name()}, "/")
|
|
|
|
w.Header().Set("Content-Type", application)
|
|
|
|
d := fmt.Sprintf(`{"code": 0,"data": %s,"reason": "","message": ""}`, string(data))
|
|
|
|
_, err = w.Write([]byte(d))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ErrorEncoderPro(w stdhttp.ResponseWriter, r *stdhttp.Request, err error) {
|
|
se := errors.FromError(err)
|
|
if _, ok := err.(*errors.Error); !ok {
|
|
se.Reason = "InternalServerError"
|
|
se.Code = stdhttp.StatusInternalServerError
|
|
se.Message = "internal server error"
|
|
}
|
|
|
|
codec, _ := http.CodecForRequest(r, "Accept")
|
|
body, err := codec.Marshal(se)
|
|
if err != nil {
|
|
w.WriteHeader(stdhttp.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", ContentType(codec.Name()))
|
|
w.WriteHeader(int(se.Code))
|
|
_, _ = w.Write(body)
|
|
}
|
|
|
|
// ContentType returns the content-type with base prefix.
|
|
func ContentType(subtype string) string {
|
|
return strings.Join([]string{baseContentType, subtype}, "/")
|
|
}
|
|
|