1 Star 0 Fork 0

tomatomeatman / GolangRepository

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
UrlUtil.go 15.33 KB
一键复制 编辑 原始数据 按行查看 历史
laowei 提交于 2024-04-03 17:34 . 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
package url
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
"gitee.com/tomatomeatman/golang-repository/bricks/model"
. "gitee.com/tomatomeatman/golang-repository/bricks/model"
. "gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data"
Log "github.com/cihub/seelog"
"github.com/gin-gonic/gin"
"github.com/shopspring/decimal"
)
type UrlUtil struct{}
// 取头参数
func (this UrlUtil) GetHeader(ctx *gin.Context) map[string]string {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
result := map[string]string{}
header := ctx.Request.Header
for key, value := range header {
if (nil == value) || (len(value) < 1) {
continue
}
result[key] = value[0]
}
return result
}
// 取所有参数,并转换成对应实体属性类型(map[string]interface{})
func (this UrlUtil) AllParams(ctx *gin.Context, entity interface{}) (map[string][]string, map[string]string, map[string][]string) {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
//-- 取头参数 --//
headerParam := map[string][]string{}
header := ctx.Request.Header
for key, value := range header {
if (nil == value) || (len(value) < 1) {
continue
}
headerParam[key] = value
}
postParam := map[string]string{}
//-- 取Post方式json参数 --//
// 检查是否为post请求
// if ctx.Request.Method != http.MethodPost {
// w.WriteHeader(http.StatusMethodNotAllowed)
// fmt.Fprintf(w, "invalid_http_method")
// return
// }
br, _ := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(br))
json.NewDecoder(bytes.NewBuffer(br)).Decode(&postParam)
//-- 取Get参数 --//
getParam := map[string][]string{}
query := ctx.Request.URL.Query()
for key, value := range query {
if (nil == value) || (len(value) < 1) {
continue
}
getParam[key] = value
}
//-- 取属性的参数 --//
form := ctx.Request.Form
if nil != form {
for key, value := range form {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := getParam[key]
if ok && (len(val) > 0) && (val[0] != "") {
continue //如果已经存在则不覆盖
}
getParam[key] = value
}
}
return headerParam, postParam, getParam
}
// 取所有参数(map[string]interface{})
func (this UrlUtil) GetParamsAll(ctx *gin.Context, addHeader bool) map[string]interface{} {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
params := make(map[string]interface{})
//-- 取Post方式json参数 --//
// 检查是否为post请求
// if ctx.Request.Method != http.MethodPost {
// w.WriteHeader(http.StatusMethodNotAllowed)
// fmt.Fprintf(w, "invalid_http_method")
// return
// }
br, _ := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(br))
json.NewDecoder(bytes.NewBuffer(br)).Decode(&params)
//-- 取头参数 --//
if addHeader {
header := ctx.Request.Header
for key, value := range header {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := params[key]
if ok && ("" != val) {
continue //如果已经存在则不覆盖
}
params[key] = value[0]
}
}
//-- 取Get参数 --//
query := ctx.Request.URL.Query()
for key, value := range query {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := params[key]
if ok && ("" != val) {
continue //如果已经存在则不覆盖
}
params[key] = value[0]
}
//-- 取属性的参数 --//
form := ctx.Request.Form
if nil != form {
for key, value := range form {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := params[key]
if ok && ("" != val) {
continue //如果已经存在则不覆盖
}
params[key] = value[0]
}
}
return params
}
// 取所有参数,并转换成对应实体属性类型(map[string]interface{})
func (this UrlUtil) GetParams(ctx *gin.Context, entity interface{}) *MsgEmity {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
params := make(map[string]string)
//-- 取Post方式json参数 --//
// 检查是否为post请求
// if ctx.Request.Method != http.MethodPost {
// w.WriteHeader(http.StatusMethodNotAllowed)
// fmt.Fprintf(w, "invalid_http_method")
// return
// }
br, _ := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(br))
json.NewDecoder(bytes.NewBuffer(br)).Decode(&params)
//-- 取头参数 --//
header := ctx.Request.Header
for key, value := range header {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := params[key]
if ok && ("" != val) {
continue //如果已经存在则不覆盖
}
params[key] = value[0]
}
//-- 取Get参数 --//
query := ctx.Request.URL.Query()
for key, value := range query {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := params[key]
if ok && ("" != val) {
continue //如果已经存在则不覆盖
}
params[key] = value[0]
}
//-- 取属性的参数 --//
form := ctx.Request.Form
if nil != form {
for key, value := range form {
if (nil == value) || (len(value) < 1) || (strings.TrimSpace(value[0]) == "") {
continue
}
val, ok := params[key]
if ok && ("" != val) {
continue //如果已经存在则不覆盖
}
params[key] = value[0]
}
}
return this.Filter(params, entity)
}
// 过滤map中不存在结构体中的属性,并转换成对应类型(map[string]interface{})
func (this UrlUtil) Filter(data map[string]string, entity interface{}) *MsgEmity {
if len(data) < 1 {
return MsgEmity{}.Err(1001, "待转换数据为空") //make(map[string]interface{})
}
var rve reflect.Value
typeOf := reflect.TypeOf(entity) //通过反射获取type定义
if typeOf.Kind() == reflect.Ptr { //是否指针类型
rve = reflect.ValueOf(entity).Elem() // 取得struct变量的指针
} else if "reflect.Value" == typeOf.String() {
if entity.(reflect.Value).Kind() == reflect.Ptr {
rve = entity.(reflect.Value).Elem()
} else if entity.(reflect.Value).Kind() == reflect.Struct {
rve = entity.(reflect.Value)
} else {
rve = entity.(reflect.Value)
}
} else {
rve = reflect.ValueOf(entity)
}
result := make(map[string]interface{})
for k, v := range data {
field := rve.FieldByName("G" + k)
if !field.IsValid() {
continue
}
vType := field.Type().Name()
switch vType {
case "int":
val, _ := strconv.Atoi(v)
result[k] = val
case "string":
result[k] = v
case "int64":
val, _ := strconv.ParseInt(v, 10, 64)
result[k] = val
case "time.Time":
val, _ := time.ParseInLocation("2006-01-02 15:04:05", v, time.Local)
result[k] = val
case "Time":
val, _ := time.ParseInLocation("2006-01-02 15:04:05", v, time.Local)
result[k] = val
case "time":
val, _ := time.ParseInLocation("2006-01-02 15:04:05", v, time.Local)
result[k] = val
case "float64":
val, _ := strconv.ParseFloat(v, 64)
result[k] = val
case "Decimal":
val, _ := decimal.NewFromString(v)
result[k] = val
case "*big.Float":
val, _ := strconv.ParseFloat(v, 64)
result[k] = big.NewFloat(val)
default:
Log.Error("'map过滤属性操作'发现无法识别的类型:" + vType)
//result[k] = v
}
}
return MsgEmity{}.Success(result, "转换结束")
}
// func (this UrlUtil) GetHearParams(ctx.Request) *MsgEmity {
// //-- 取请求头参数 --//
// header := ctx.Request.Header
// //fmt.Println("Header全部数据:", header)
// //明确给定类型
// var acc []string = header[FirstUpper("token")]
// for _, n := range acc {
// fmt.Println("Accepth内容:", n)
// }
// return MsgEmity{}.Success(9999, "map转换json字符串发生异常:")
// }
/**
* 取请求头参数
* ctx GinHttp上下文对象
* name 参数名称
* def 默认值
*/
func (this UrlUtil) GetHearParam(ctx *gin.Context, name string, def interface{}) interface{} {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
header := ctx.Request.Header
v := header[StringUtil{}.FirstUpper(name)]
if nil == v || len(v) < 1 || strings.TrimSpace(v[0]) == "" {
if def == nil {
def = ""
}
return def
}
if def == nil {
def = ""
}
switch def.(type) {
case string: // 将interface转为string字符串类型
return strings.TrimSpace(v[0])
case int:
result, err := strconv.Atoi(v[0])
if err != nil {
return def
}
return result
case int64:
result, err := strconv.ParseInt(v[0], 10, 64)
if err != nil {
return 0
}
return result
case time.Time:
result, err := time.ParseInLocation("2006-01-02 15:04:05", v[0], time.Local)
if err != nil {
return def
}
return result
case float64:
result, err := strconv.ParseFloat(v[0], 64)
if err != nil {
return def
}
return result
default:
return strings.TrimSpace(v[0])
}
}
/**
* 取参数
* ctx GinHttp上下文对象
* entity 要转换的数据类型 无视(&entity或entity)
*/
func (this UrlUtil) GetBody(ctx *gin.Context, entity interface{}) *MsgEmity {
typeOf := reflect.TypeOf(entity) //通过反射获取type定义
if typeOf.Kind() == reflect.Ptr { //是否指针类型
typeOf = typeOf.Elem()
}
if typeOf.Kind() != reflect.Struct { //不属于结构体
return UrlUtil{}.GetParams(ctx, entity)
}
result := reflect.New(typeOf).Interface() //创建同结构的指针,并转换成Interface{}, 注意不要使用reflect.New(typeOf).Elem().Interface()
br, _ := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(br)) //写回
json.NewDecoder(bytes.NewBuffer(br)).Decode(result)
return MsgEmity{}.Success(reflect.ValueOf(result).Elem().Interface(), "转换结束") //把指针转换到实际,否则会提示: interface{} is *xxx not xxx
}
/**
* 取参数
* ctx GinHttp上下文对象
* name 参数名称
* def 默认值
*/
func (this UrlUtil) GetParam(ctx *gin.Context, name string, def interface{}) interface{} {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
//-- 取头参数 --//
result := ctx.Request.Header.Get(name)
if "" != result {
return this.toInterface(result, def)
}
result = ctx.Request.Header.Get(StringUtil{}.FirstUpper(strings.ToLower(name))) //sCookie会被传递为Scookie
if "" != result {
return this.toInterface(result, def)
}
//-- 取POST方法的参数 --//
params := make(map[string]interface{})
br, _ := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(br))
json.NewDecoder(bytes.NewBuffer(br)).Decode(&params)
temp, ok := params[name]
if ok {
return this.toInterface(fmt.Sprint(temp), def)
}
temp, ok = params[StringUtil{}.FirstUpper(name)]
if ok {
return this.toInterface(fmt.Sprint(temp), def)
}
//-- 取GET方法的参数 --//
query := ctx.Request.URL.Query() // 获取请求的参数
v := query[name]
if nil != v && len(v) > 0 && strings.TrimSpace(v[0]) != "" {
return this.toInterface(v[0], def)
}
//-- 取属性的参数 --//
result = query.Get(name)
if "" != result {
return this.toInterface(result, def)
}
//-- 取form-data格式数据 --//
result = ctx.Request.FormValue(name)
if "" != result {
return this.toInterface(result, def)
}
result = ctx.PostForm(name)
if "" != result {
return this.toInterface(result, def)
}
return def
}
// 字符串转接口
func (this UrlUtil) toInterface(value string, def interface{}) interface{} {
if ("" == strings.TrimSpace(value)) && (def == nil) && (def == "") {
return def
}
if def == nil {
def = ""
}
switch def.(type) {
case string: // 将interface转为string字符串类型
return strings.TrimSpace(value)
case int:
result, err := strconv.Atoi(value)
if err != nil {
return def
}
return result
case int64:
result, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return 0
}
return result
case time.Time:
result, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local)
if err != nil {
return def
}
return result
case float32:
result, err := strconv.ParseFloat(value, 32)
if err != nil {
return def
}
return result //注意,返回去的也是float64,所以 xx.(Float32)会异常,应使用 xx.(Float64)
case float64:
result, err := strconv.ParseFloat(value, 64)
if err != nil {
return def
}
return result
default:
return strings.TrimSpace(value)
}
}
/**
* 取请求参数中的记录编号
* ctx GinHttp上下文对象
* idName 主键名称
*/
func (this UrlUtil) GetParamToId(ctx *gin.Context, idName string) interface{} {
var id interface{}
if model.TableMajorKeyAutoInt == idName {
id = UrlUtil{}.GetParam(ctx, idName, -1)
if id == -1 {
return nil
}
return id
}
id = UrlUtil{}.GetParam(ctx, idName, "")
if strings.TrimSpace(id.(string)) == "" {
return nil
}
return id
}
/**
* 取请求参数中的版本号
* ctx GinHttp上下文对象
* hasVersion (数据库表)是否有版本号
*/
func (this UrlUtil) GetParamToVersion(ctx *gin.Context, hasVersion bool) int {
var iVersion int
if hasVersion {
iVersion = UrlUtil{}.GetParam(ctx, model.TableVersionName, -1).(int)
} else {
iVersion = IntegerUtil{}.MaxInt()
}
return iVersion
}
/**
* 增加请求属性
* ctx GinHttp上下文对象
* name 属性名
* value 属性值
*/
func (this UrlUtil) AddAttrib(ctx *gin.Context, name string, value string) {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
form := ctx.Request.Form
if nil == form {
form = make(url.Values)
ctx.Request.Form = form
}
form.Set(name, value)
}
/**
* 获取请求属性
* ctx GinHttp上下文对象
* name 属性名
* value 属性值
*/
func (this UrlUtil) GetAttrib(ctx *gin.Context, name string) string {
ctx.Request.ParseForm() //警告:必须先 解析所有请求数据
form := ctx.Request.Form
if nil == form {
return ""
}
return form.Get(name)
}
// /**
// * 允许跨域访问
// * w Http响应对象
// */
// func (this UrlUtil) SetupCORS(ctx *gin.Context) {
// (*w).Header().Set("Access-Control-Allow-Origin", "*")
// (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
// (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
// }
/**
* 设置统一返回信息
* w Http响应对象
* me 统一信息
*/
func (this UrlUtil) SetResponse(ctx *gin.Context, me *MsgEmity) {
// buffer := &bytes.Buffer{}
// encoder := json.NewEncoder(buffer)
// encoder.SetEscapeHTML(false)
// err := encoder.Encode(me)
// if err != nil {
// return
// }
ctx.JSONP(http.StatusOK, me)
}
Go
1
https://gitee.com/tomatomeatman/golang-repository.git
git@gitee.com:tomatomeatman/golang-repository.git
tomatomeatman
golang-repository
GolangRepository
bcb142e03580

搜索帮助