aicra/internal/reqdata/parameter.go

96 lines
1.9 KiB
Go
Raw Normal View History

package reqdata
2018-06-01 08:51:51 +00:00
2019-11-19 15:14:50 +00:00
import (
"encoding/json"
"fmt"
"reflect"
)
2019-04-30 22:02:28 +00:00
// Parameter represents an http request parameter
// that can be of type URL, GET, or FORM (multipart, json, urlencoded)
type Parameter struct {
// whether the value has been json-parsed
// for optimisation purpose, parameters are only parsed
// if they are required by the current service
2019-04-30 22:02:28 +00:00
Parsed bool
// whether the value is a file
File bool
// the actual parameter value
Value interface{}
}
2018-06-01 08:51:51 +00:00
// Parse parameter (json-like) if not already done
func (i *Parameter) Parse() {
2018-06-01 08:51:51 +00:00
/* ignore already parsed or nil*/
2018-06-01 08:51:51 +00:00
if i.Parsed || i.Value == nil {
return
2020-02-28 16:50:55 +00:00
}
/* parse value */
i.Parsed = true
i.Value = parseParameter(i.Value)
2018-06-01 08:51:51 +00:00
}
2019-11-19 15:14:50 +00:00
// parseParameter parses http URI/GET/POST data
// - []string : return array of json elements
// - string : return json if valid, else return raw string
func parseParameter(data interface{}) interface{} {
2019-11-19 15:14:50 +00:00
dtype := reflect.TypeOf(data)
dvalue := reflect.ValueOf(data)
switch dtype.Kind() {
/* (1) []string -> recursive */
case reflect.Slice:
// 1. ignore empty
2019-11-19 15:14:50 +00:00
if dvalue.Len() == 0 {
return data
2019-11-19 15:14:50 +00:00
}
// 2. parse each element recursively
2019-11-19 15:14:50 +00:00
result := make([]interface{}, dvalue.Len())
for i, l := 0, dvalue.Len(); i < l; i++ {
element := dvalue.Index(i)
result[i] = parseParameter(element.Interface())
2019-11-19 15:14:50 +00:00
}
return result
2019-11-19 15:14:50 +00:00
/* (2) string -> parse */
case reflect.String:
// build json wrapper
wrapper := fmt.Sprintf("{\"wrapped\":%s}", dvalue.String())
// try to parse as json
var result interface{}
err := json.Unmarshal([]byte(wrapper), &result)
// return if success
if err != nil {
return dvalue.String()
}
2019-11-19 15:14:50 +00:00
mapval, ok := result.(map[string]interface{})
if !ok {
return dvalue.String()
}
2019-11-19 15:14:50 +00:00
wrapped, ok := mapval["wrapped"]
if !ok {
return dvalue.String()
2019-11-19 15:14:50 +00:00
}
return wrapped
2019-11-19 15:14:50 +00:00
}
/* (3) NIL if unknown type */
return dvalue.Interface()
2019-11-19 15:14:50 +00:00
}