package gnet

import (
	"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 读取客户端请求数据
// Deprecated: 已弃用, 请使用 gio.ReadLimit 替代
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 {
		var maxBytesError *http.MaxBytesError
		if errors.As(err, &maxBytesError) {
			return nil, errors.New(http.StatusText(http.StatusRequestEntityTooLarge))
		}
		return nil, errors.New(http.StatusText(http.StatusBadRequest))
	}
	return b, nil
}

// ReadResponseBody 用于 HTTP client 读取服务器返回数据
// Deprecated: 已弃用, 请使用 gio.ReadLimit 替代
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{}
)
