1 Star 0 Fork 0

liujinsuo / tool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
http.go 2.43 KB
一键复制 编辑 原始数据 按行查看 历史
liujinsuo 提交于 2023-06-17 12:51 . GetRequestParam
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)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/liujinsuo/tool.git
git@gitee.com:liujinsuo/tool.git
liujinsuo
tool
tool
a2d70a724a04

搜索帮助

344bd9b3 5694891 D2dac590 5694891