| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 | package networkimport (	"errors"	"io"	"net/http")const (	HTTPContentTypeJson = "application/json; charset=utf-8")type httpCommon struct{}func (httpCommon) Error(w http.ResponseWriter, code int) {	http.Error(w, http.StatusText(code), code)}func (httpCommon) ErrJson(w http.ResponseWriter, code int, b []byte) {	w.Header().Set("Content-Type", HTTPContentTypeJson)	w.Header().Set("X-Content-Type-Options", "nosniff")	w.WriteHeader(code)	_, _ = w.Write(b)}// ReadRequestBody 用于 HTTP server 读取客户端请求数据func (httpCommon) ReadRequestBody(w http.ResponseWriter, r *http.Request, size int64) ([]byte, error) {	if size <= 0 {		return io.ReadAll(r.Body)	}	b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, size))	if err != nil {		if _, ok := err.(*http.MaxBytesError); ok {			return nil, errors.New(http.StatusText(http.StatusRequestEntityTooLarge))		}		return nil, errors.New(http.StatusText(http.StatusBadRequest))	}	return b, nil}// ReadResponseBody 用于 HTTP client 读取服务器返回数据func (httpCommon) ReadResponseBody(r *http.Response, size int64) ([]byte, error) {	defer func() {		_ = r.Body.Close()	}()	if size <= 0 {		return io.ReadAll(r.Body)	}	b := make([]byte, size)	n, err := r.Body.Read(b)	if err != nil {		return nil, err	}	return b[:n], nil}var (	HTTP = &httpCommon{})
 |