代码拉取完成,页面将自动刷新
package toolhttp
import (
"bytes"
"gitee.com/liujinsuo/tool"
"github.com/pkg/errors"
"io"
"net"
"net/http"
"reflect"
"strings"
)
type httpT struct {
}
// GetResponseStatus 获取响应状态与响应body
func (s *httpT) GetResponseStatus(w http.ResponseWriter) (status int, body []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = errors.Errorf("panic %+v", r)
}
}()
v := reflect.ValueOf(w).Elem()
status = int(v.FieldByName("status").Int()) //状态
responseW := v.FieldByName("w")
if responseW.IsNil() == true {
return //没有响应body
} else {
n := responseW.Elem().FieldByName("n").Int()
body = responseW.Elem().FieldByName("buf").Bytes()[:n] //body
}
return
}
// GetRequestParam 获取请求参数
func (s *httpT) GetRequestParam(r *http.Request) ([]byte, error) {
ContentType := r.Header.Get("Content-Type")
if strings.Contains(ContentType, "multipart/form-data") == true {
return nil, nil
}
if r.Method == http.MethodGet ||
r.Method == http.MethodOptions ||
r.Method == http.MethodHead ||
r.Method == http.MethodDelete {
return nil, nil
}
//读取body
p, err := io.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrap(err, "读取body失败")
}
//写回去
r.Body = io.NopCloser(bytes.NewReader(p))
if ContentType == "application/json" {
if len(p) <= 0 {
return nil, nil
}
//压缩json
if r, err := tool.JsonCompression(p); err != nil {
return nil, errors.Wrap(err, "压缩json失败")
} else {
return r, nil
}
} else if ContentType == "application/x-www-form-urlencoded" {
return p, nil
} else {
return p, nil
}
}
// ClientIP 尽最大努力实现获取客户端 IP 的算法。
// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。
func (s *httpT) ClientIP(r *http.Request) string {
xForwardedFor := r.Header.Get("X-Forwarded-For")
ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
if ip != "" {
return ip
}
ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
if ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
return ip
}
return ""
}
// RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).
func (s *httpT) RemoteIP(r *http.Request) string {
ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
if err != nil {
return ""
}
return ip
}
var HTTP = new(httpT)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。