encode.go 779 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
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
package resutil

import (
	"encoding/json"
	"github.com/go-kratos/kratos/v2/log"
	"net/http"
)

func HttpResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error {
	if v == nil {
		_, err := w.Write(nil)
		return err
	}
	data, err := json.Marshal(MakeHttpSuccess(v))
	if err != nil {
		return err
	}

	w.Header().Set("Content-Type", "application/json")
	_, err = w.Write(data)
	if err != nil {
		return err
	}
	return nil
}

func HttpErrorEncoder(w http.ResponseWriter, r *http.Request, err error) {
	data, err := json.Marshal(MakeHttpError(err))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Errorf("HttpErrorEncoder json编码失败: %s", err)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_, _ = w.Write(data)
}