1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-23 05:30:55 +00:00
Beego/context/input.go

663 lines
18 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2013-08-21 09:59:31 +00:00
package context
2013-08-21 05:24:14 +00:00
import (
"bytes"
"compress/gzip"
2014-04-05 16:08:03 +00:00
"errors"
"io"
2013-08-21 05:24:14 +00:00
"io/ioutil"
2017-08-09 19:05:06 +00:00
"net"
2017-07-04 13:16:59 +00:00
"net/http"
"net/url"
"reflect"
"regexp"
2013-08-21 05:24:14 +00:00
"strconv"
"strings"
2013-12-03 13:37:39 +00:00
"github.com/astaxie/beego/session"
2013-08-21 05:24:14 +00:00
)
// Regexes for checking the accept headers
// TODO make sure these are correct
var (
2015-09-10 07:31:09 +00:00
acceptsHTMLRegex = regexp.MustCompile(`(text/html|application/xhtml\+xml)(?:,|$)`)
acceptsXMLRegex = regexp.MustCompile(`(application/xml|text/xml)(?:,|$)`)
acceptsJSONRegex = regexp.MustCompile(`(application/json)(?:,|$)`)
2015-12-16 15:11:03 +00:00
maxParam = 50
)
// BeegoInput operates the http request header, data, cookie and body.
2013-12-25 12:13:38 +00:00
// it also contains router params and current session.
2013-08-21 05:24:14 +00:00
type BeegoInput struct {
2016-09-15 12:04:45 +00:00
Context *Context
CruSession session.Store
pnames []string
pvalues []string
data map[interface{}]interface{} // store some values in this context when calling context in filter or controller.
RequestBody []byte
RunMethod string
RunController reflect.Type
2013-08-21 05:24:14 +00:00
}
2015-12-10 13:59:54 +00:00
// NewInput return BeegoInput generated by Context.
func NewInput() *BeegoInput {
2013-08-21 05:24:14 +00:00
return &BeegoInput{
2015-12-16 15:43:32 +00:00
pnames: make([]string, 0, maxParam),
pvalues: make([]string, 0, maxParam),
2015-12-16 15:11:03 +00:00
data: make(map[interface{}]interface{}),
2013-08-21 05:24:14 +00:00
}
}
2015-12-10 13:59:54 +00:00
// Reset init the BeegoInput
func (input *BeegoInput) Reset(ctx *Context) {
input.Context = ctx
input.CruSession = nil
2015-12-16 15:11:03 +00:00
input.pnames = input.pnames[:0]
2015-12-16 15:43:32 +00:00
input.pvalues = input.pvalues[:0]
2015-12-16 15:11:03 +00:00
input.data = nil
2015-12-10 13:59:54 +00:00
input.RequestBody = []byte{}
}
2013-12-25 12:13:38 +00:00
// Protocol returns request protocol name, such as HTTP/1.1 .
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Protocol() string {
2015-12-10 13:59:54 +00:00
return input.Context.Request.Proto
2013-08-21 05:24:14 +00:00
}
2015-09-10 07:31:09 +00:00
// URI returns full request url with query string, fragment.
func (input *BeegoInput) URI() string {
2015-12-10 13:59:54 +00:00
return input.Context.Request.RequestURI
2013-08-21 05:24:14 +00:00
}
2015-09-10 07:31:09 +00:00
// URL returns request url path (without query string, fragment).
func (input *BeegoInput) URL() string {
2015-12-10 13:59:54 +00:00
return input.Context.Request.URL.Path
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Site returns base site url as scheme://domain type.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Site() string {
return input.Scheme() + "://" + input.Domain()
}
2013-12-25 12:13:38 +00:00
// Scheme returns request scheme as "http" or "https".
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Scheme() string {
if scheme := input.Header("X-Forwarded-Proto"); scheme != "" {
return scheme
}
2015-12-10 13:59:54 +00:00
if input.Context.Request.URL.Scheme != "" {
return input.Context.Request.URL.Scheme
}
2015-12-10 13:59:54 +00:00
if input.Context.Request.TLS == nil {
2013-09-26 14:31:39 +00:00
return "http"
}
return "https"
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Domain returns host name.
// Alias of Host method.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Domain() string {
return input.Host()
}
2013-12-25 12:13:38 +00:00
// Host returns host name.
// if no host info in request, return localhost.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Host() string {
2015-12-10 13:59:54 +00:00
if input.Context.Request.Host != "" {
2017-08-09 08:23:03 +00:00
if hostPart, _, err := net.SplitHostPort(input.Context.Request.Host); err == nil {
return hostPart
2013-08-21 05:24:14 +00:00
}
2015-12-10 13:59:54 +00:00
return input.Context.Request.Host
2013-08-21 05:24:14 +00:00
}
return "localhost"
}
2013-12-25 12:13:38 +00:00
// Method returns http request method.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Method() string {
2015-12-10 13:59:54 +00:00
return input.Context.Request.Method
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Is returns boolean of this request is on given method, such as Is("POST").
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Is(method string) bool {
return input.Method() == method
}
2015-09-10 07:31:09 +00:00
// IsGet Is this a GET method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsGet() bool {
return input.Is("GET")
}
2015-09-10 07:31:09 +00:00
// IsPost Is this a POST method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsPost() bool {
return input.Is("POST")
}
2015-09-10 07:31:09 +00:00
// IsHead Is this a Head method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsHead() bool {
return input.Is("HEAD")
}
2015-09-10 07:31:09 +00:00
// IsOptions Is this a OPTIONS method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsOptions() bool {
return input.Is("OPTIONS")
}
2015-09-10 07:31:09 +00:00
// IsPut Is this a PUT method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsPut() bool {
return input.Is("PUT")
}
2015-09-10 07:31:09 +00:00
// IsDelete Is this a DELETE method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsDelete() bool {
return input.Is("DELETE")
}
2015-09-10 07:31:09 +00:00
// IsPatch Is this a PATCH method request?
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) IsPatch() bool {
return input.Is("PATCH")
}
2013-12-25 12:13:38 +00:00
// IsAjax returns boolean of this request is generated by ajax.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) IsAjax() bool {
2013-10-29 07:45:45 +00:00
return input.Header("X-Requested-With") == "XMLHttpRequest"
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// IsSecure returns boolean of this request is in https.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) IsSecure() bool {
return input.Scheme() == "https"
}
// IsWebsocket returns boolean of this request is in webSocket.
2013-09-10 09:02:56 +00:00
func (input *BeegoInput) IsWebsocket() bool {
return input.Header("Upgrade") == "websocket"
}
// IsUpload returns boolean of whether file uploads in this request or not..
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) IsUpload() bool {
return strings.Contains(input.Header("Content-Type"), "multipart/form-data")
2013-08-21 05:24:14 +00:00
}
2015-09-10 07:31:09 +00:00
// AcceptsHTML Checks if request accepts html response
func (input *BeegoInput) AcceptsHTML() bool {
return acceptsHTMLRegex.MatchString(input.Header("Accept"))
}
2015-09-10 07:31:09 +00:00
// AcceptsXML Checks if request accepts xml response
func (input *BeegoInput) AcceptsXML() bool {
return acceptsXMLRegex.MatchString(input.Header("Accept"))
}
2015-09-10 07:31:09 +00:00
// AcceptsJSON Checks if request accepts json response
func (input *BeegoInput) AcceptsJSON() bool {
return acceptsJSONRegex.MatchString(input.Header("Accept"))
}
2013-12-25 12:13:38 +00:00
// IP returns request client ip.
// if in proxy, return first proxy id.
2017-08-09 08:23:03 +00:00
// if error, return RemoteAddr.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) IP() string {
ips := input.Proxy()
if len(ips) > 0 && ips[0] != "" {
2017-08-09 08:23:03 +00:00
rip, _, err := net.SplitHostPort(ips[0])
if err != nil {
rip = ips[0]
}
2017-08-09 08:23:03 +00:00
return rip
}
if ip, _, err := net.SplitHostPort(input.Context.Request.RemoteAddr); err == nil {
return ip
2013-08-21 05:24:14 +00:00
}
2017-08-09 08:23:03 +00:00
return input.Context.Request.RemoteAddr
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Proxy returns proxy client ips slice.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Proxy() []string {
2013-11-21 07:59:16 +00:00
if ips := input.Header("X-Forwarded-For"); ips != "" {
2013-08-21 05:24:14 +00:00
return strings.Split(ips, ",")
}
return []string{}
}
// Referer returns http referer header.
func (input *BeegoInput) Referer() string {
return input.Header("Referer")
}
2013-12-25 12:13:38 +00:00
// Refer returns http referer header.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Refer() string {
return input.Referer()
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// SubDomains returns sub domain string.
// if aa.bb.domain.com, returns aa.bb .
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) SubDomains() string {
parts := strings.Split(input.Host(), ".")
if len(parts) >= 3 {
return strings.Join(parts[:len(parts)-2], ".")
}
return ""
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Port returns request client port.
// when error or empty, return 80.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Port() int {
2017-08-09 08:23:03 +00:00
if _, portPart, err := net.SplitHostPort(input.Context.Request.Host); err == nil {
port, _ := strconv.Atoi(portPart)
2013-08-21 05:24:14 +00:00
return port
}
return 80
}
2013-12-25 12:13:38 +00:00
// UserAgent returns request client user agent string.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) UserAgent() string {
2013-11-21 07:59:16 +00:00
return input.Header("User-Agent")
2013-08-21 05:24:14 +00:00
}
2015-12-16 15:11:03 +00:00
// ParamsLen return the length of the params
func (input *BeegoInput) ParamsLen() int {
return len(input.pnames)
}
2013-12-25 12:13:38 +00:00
// Param returns router param by a given key.
2013-11-26 03:05:49 +00:00
func (input *BeegoInput) Param(key string) string {
2015-12-16 15:11:03 +00:00
for i, v := range input.pnames {
2015-12-16 15:43:32 +00:00
if v == key && i <= len(input.pvalues) {
2015-12-16 15:11:03 +00:00
return input.pvalues[i]
}
2013-08-21 05:24:14 +00:00
}
return ""
}
2016-01-07 17:20:34 +00:00
// Params returns the map[key]value.
func (input *BeegoInput) Params() map[string]string {
m := make(map[string]string)
for i, v := range input.pnames {
if i <= len(input.pvalues) {
m[v] = input.pvalues[i]
}
}
return m
}
2015-12-16 15:11:03 +00:00
// SetParam will set the param with key and value
func (input *BeegoInput) SetParam(key, val string) {
// check if already exists
for i, v := range input.pnames {
if v == key && i <= len(input.pvalues) {
input.pvalues[i] = val
return
}
}
2015-12-16 15:43:32 +00:00
input.pvalues = append(input.pvalues, val)
2015-12-16 15:11:03 +00:00
input.pnames = append(input.pnames, key)
}
// ResetParams clears any of the input's Params
// This function is used to clear parameters so they may be reset between filter
// passes.
func (input *BeegoInput) ResetParams() {
input.pnames = input.pnames[:0]
input.pvalues = input.pvalues[:0]
}
2013-12-25 12:13:38 +00:00
// Query returns input data item string by a given string.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Query(key string) string {
2014-04-10 14:20:46 +00:00
if val := input.Param(key); val != "" {
return val
}
2015-12-10 13:59:54 +00:00
if input.Context.Request.Form == nil {
input.Context.Request.ParseForm()
2014-04-05 16:08:03 +00:00
}
2015-12-10 13:59:54 +00:00
return input.Context.Request.Form.Get(key)
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Header returns request header item string by a given string.
// if non-existed, return empty string.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Header(key string) string {
2015-12-10 13:59:54 +00:00
return input.Context.Request.Header.Get(key)
2013-08-21 05:24:14 +00:00
}
2013-12-25 12:13:38 +00:00
// Cookie returns request cookie item string by a given key.
// if non-existed, return empty string.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Cookie(key string) string {
2015-12-10 13:59:54 +00:00
ck, err := input.Context.Request.Cookie(key)
2013-08-21 05:24:14 +00:00
if err != nil {
return ""
}
return ck.Value
}
2013-12-25 12:13:38 +00:00
// Session returns current session item value by a given key.
2016-08-18 16:11:19 +00:00
// if non-existed, return nil.
2013-08-21 05:24:14 +00:00
func (input *BeegoInput) Session(key interface{}) interface{} {
return input.CruSession.Get(key)
}
// CopyBody returns the raw request body data as bytes.
func (input *BeegoInput) CopyBody(MaxMemory int64) []byte {
2016-08-18 16:31:46 +00:00
if input.Context.Request.Body == nil {
return []byte{}
}
var requestbody []byte
2015-12-21 08:23:31 +00:00
safe := &io.LimitedReader{R: input.Context.Request.Body, N: MaxMemory}
if input.Header("Content-Encoding") == "gzip" {
reader, err := gzip.NewReader(safe)
if err != nil {
return nil
}
requestbody, _ = ioutil.ReadAll(reader)
} else {
requestbody, _ = ioutil.ReadAll(safe)
}
2015-12-10 13:59:54 +00:00
input.Context.Request.Body.Close()
2013-08-21 05:24:14 +00:00
bf := bytes.NewBuffer(requestbody)
2017-07-04 13:16:59 +00:00
input.Context.Request.Body = http.MaxBytesReader(input.Context.ResponseWriter, ioutil.NopCloser(bf), MaxMemory)
2013-09-09 15:17:51 +00:00
input.RequestBody = requestbody
2013-08-21 05:24:14 +00:00
return requestbody
}
2013-11-26 03:05:49 +00:00
2015-12-16 15:11:03 +00:00
// Data return the implicit data in the input
func (input *BeegoInput) Data() map[interface{}]interface{} {
if input.data == nil {
input.data = make(map[interface{}]interface{})
}
return input.data
}
2013-12-25 12:13:38 +00:00
// GetData returns the stored data in this context.
2013-11-26 03:05:49 +00:00
func (input *BeegoInput) GetData(key interface{}) interface{} {
2015-12-16 15:11:03 +00:00
if v, ok := input.data[key]; ok {
2013-11-26 03:05:49 +00:00
return v
}
return nil
}
2013-12-25 12:13:38 +00:00
// SetData stores data with given key in this context.
// This data are only available in this context.
2013-11-26 03:05:49 +00:00
func (input *BeegoInput) SetData(key, val interface{}) {
2015-12-16 15:11:03 +00:00
if input.data == nil {
input.data = make(map[interface{}]interface{})
}
input.data[key] = val
2013-11-26 03:05:49 +00:00
}
2014-04-05 16:08:03 +00:00
2015-09-10 07:31:09 +00:00
// ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type
2014-04-05 16:08:03 +00:00
func (input *BeegoInput) ParseFormOrMulitForm(maxMemory int64) error {
// Parse the body depending on the content type.
2014-04-14 21:05:53 +00:00
if strings.Contains(input.Header("Content-Type"), "multipart/form-data") {
2015-12-10 13:59:54 +00:00
if err := input.Context.Request.ParseMultipartForm(maxMemory); err != nil {
2014-04-05 16:08:03 +00:00
return errors.New("Error parsing request body:" + err.Error())
}
2015-12-10 13:59:54 +00:00
} else if err := input.Context.Request.ParseForm(); err != nil {
2014-04-14 21:05:53 +00:00
return errors.New("Error parsing request body:" + err.Error())
2014-04-05 16:08:03 +00:00
}
return nil
}
// Bind data from request.Form[key] to dest
// like /?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie
// var id int beegoInput.Bind(&id, "id") id ==123
2015-04-07 02:35:18 +00:00
// var isok bool beegoInput.Bind(&isok, "isok") isok ==true
// var ft float64 beegoInput.Bind(&ft, "ft") ft ==1.2
// ol := make([]int, 0, 2) beegoInput.Bind(&ol, "ol") ol ==[1 2]
// ul := make([]string, 0, 2) beegoInput.Bind(&ul, "ul") ul ==[str array]
// user struct{Name} beegoInput.Bind(&user, "user") user == {Name:"astaxie"}
func (input *BeegoInput) Bind(dest interface{}, key string) error {
value := reflect.ValueOf(dest)
if value.Kind() != reflect.Ptr {
return errors.New("beego: non-pointer passed to Bind: " + key)
}
value = value.Elem()
if !value.CanSet() {
return errors.New("beego: non-settable variable passed to Bind: " + key)
}
2017-03-04 12:23:55 +00:00
typ := value.Type()
// Get real type if dest define with interface{}.
// e.g var dest interface{} dest=1.0
if value.Kind() == reflect.Interface {
typ = value.Elem().Type()
}
rv := input.bind(key, typ)
if !rv.IsValid() {
return errors.New("beego: reflect value is empty")
}
value.Set(rv)
return nil
}
func (input *BeegoInput) bind(key string, typ reflect.Type) reflect.Value {
2017-03-04 12:23:55 +00:00
if input.Context.Request.Form == nil {
input.Context.Request.ParseForm()
}
2015-07-06 05:54:14 +00:00
rv := reflect.Zero(typ)
switch typ.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
val := input.Query(key)
if len(val) == 0 {
return rv
}
rv = input.bindInt(val, typ)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
val := input.Query(key)
if len(val) == 0 {
return rv
}
rv = input.bindUint(val, typ)
case reflect.Float32, reflect.Float64:
val := input.Query(key)
if len(val) == 0 {
return rv
}
rv = input.bindFloat(val, typ)
case reflect.String:
val := input.Query(key)
if len(val) == 0 {
return rv
}
rv = input.bindString(val, typ)
case reflect.Bool:
val := input.Query(key)
if len(val) == 0 {
return rv
}
rv = input.bindBool(val, typ)
case reflect.Slice:
2015-12-10 13:59:54 +00:00
rv = input.bindSlice(&input.Context.Request.Form, key, typ)
case reflect.Struct:
2015-12-10 13:59:54 +00:00
rv = input.bindStruct(&input.Context.Request.Form, key, typ)
case reflect.Ptr:
rv = input.bindPoint(key, typ)
case reflect.Map:
2015-12-10 13:59:54 +00:00
rv = input.bindMap(&input.Context.Request.Form, key, typ)
}
return rv
}
func (input *BeegoInput) bindValue(val string, typ reflect.Type) reflect.Value {
2015-07-06 05:54:14 +00:00
rv := reflect.Zero(typ)
switch typ.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
rv = input.bindInt(val, typ)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
rv = input.bindUint(val, typ)
case reflect.Float32, reflect.Float64:
rv = input.bindFloat(val, typ)
case reflect.String:
rv = input.bindString(val, typ)
case reflect.Bool:
rv = input.bindBool(val, typ)
case reflect.Slice:
rv = input.bindSlice(&url.Values{"": {val}}, "", typ)
case reflect.Struct:
rv = input.bindStruct(&url.Values{"": {val}}, "", typ)
case reflect.Ptr:
rv = input.bindPoint(val, typ)
case reflect.Map:
rv = input.bindMap(&url.Values{"": {val}}, "", typ)
}
return rv
}
func (input *BeegoInput) bindInt(val string, typ reflect.Type) reflect.Value {
intValue, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return reflect.Zero(typ)
}
pValue := reflect.New(typ)
pValue.Elem().SetInt(intValue)
return pValue.Elem()
}
func (input *BeegoInput) bindUint(val string, typ reflect.Type) reflect.Value {
uintValue, err := strconv.ParseUint(val, 10, 64)
if err != nil {
return reflect.Zero(typ)
}
pValue := reflect.New(typ)
pValue.Elem().SetUint(uintValue)
return pValue.Elem()
}
func (input *BeegoInput) bindFloat(val string, typ reflect.Type) reflect.Value {
floatValue, err := strconv.ParseFloat(val, 64)
if err != nil {
return reflect.Zero(typ)
}
pValue := reflect.New(typ)
pValue.Elem().SetFloat(floatValue)
return pValue.Elem()
}
func (input *BeegoInput) bindString(val string, typ reflect.Type) reflect.Value {
return reflect.ValueOf(val)
}
func (input *BeegoInput) bindBool(val string, typ reflect.Type) reflect.Value {
val = strings.TrimSpace(strings.ToLower(val))
switch val {
case "true", "on", "1":
return reflect.ValueOf(true)
}
return reflect.ValueOf(false)
}
type sliceValue struct {
index int // Index extracted from brackets. If -1, no index was provided.
value reflect.Value // the bound value for this slice element.
}
func (input *BeegoInput) bindSlice(params *url.Values, key string, typ reflect.Type) reflect.Value {
maxIndex := -1
numNoIndex := 0
sliceValues := []sliceValue{}
for reqKey, vals := range *params {
if !strings.HasPrefix(reqKey, key+"[") {
continue
}
// Extract the index, and the index where a sub-key starts. (e.g. field[0].subkey)
index := -1
leftBracket, rightBracket := len(key), strings.Index(reqKey[len(key):], "]")+len(key)
if rightBracket > leftBracket+1 {
index, _ = strconv.Atoi(reqKey[leftBracket+1 : rightBracket])
}
subKeyIndex := rightBracket + 1
// Handle the indexed case.
if index > -1 {
if index > maxIndex {
maxIndex = index
}
sliceValues = append(sliceValues, sliceValue{
index: index,
value: input.bind(reqKey[:subKeyIndex], typ.Elem()),
})
continue
}
// It's an un-indexed element. (e.g. element[])
numNoIndex += len(vals)
for _, val := range vals {
// Unindexed values can only be direct-bound.
sliceValues = append(sliceValues, sliceValue{
index: -1,
value: input.bindValue(val, typ.Elem()),
})
}
}
resultArray := reflect.MakeSlice(typ, maxIndex+1, maxIndex+1+numNoIndex)
for _, sv := range sliceValues {
if sv.index != -1 {
resultArray.Index(sv.index).Set(sv.value)
} else {
resultArray = reflect.Append(resultArray, sv.value)
}
}
return resultArray
}
func (input *BeegoInput) bindStruct(params *url.Values, key string, typ reflect.Type) reflect.Value {
result := reflect.New(typ).Elem()
fieldValues := make(map[string]reflect.Value)
for reqKey, val := range *params {
2016-08-24 08:04:22 +00:00
var fieldName string
if strings.HasPrefix(reqKey, key+".") {
fieldName = reqKey[len(key)+1:]
} else if strings.HasPrefix(reqKey, key+"[") && reqKey[len(reqKey)-1] == ']' {
fieldName = reqKey[len(key)+1 : len(reqKey)-1]
} else {
continue
}
if _, ok := fieldValues[fieldName]; !ok {
// Time to bind this field. Get it and make sure we can set it.
fieldValue := result.FieldByName(fieldName)
if !fieldValue.IsValid() {
continue
}
if !fieldValue.CanSet() {
continue
}
boundVal := input.bindValue(val[0], fieldValue.Type())
fieldValue.Set(boundVal)
fieldValues[fieldName] = boundVal
}
}
return result
}
func (input *BeegoInput) bindPoint(key string, typ reflect.Type) reflect.Value {
return input.bind(key, typ.Elem()).Addr()
}
func (input *BeegoInput) bindMap(params *url.Values, key string, typ reflect.Type) reflect.Value {
var (
result = reflect.MakeMap(typ)
keyType = typ.Key()
valueType = typ.Elem()
)
for paramName, values := range *params {
if !strings.HasPrefix(paramName, key+"[") || paramName[len(paramName)-1] != ']' {
continue
}
key := paramName[len(key)+1 : len(paramName)-1]
result.SetMapIndex(input.bindValue(key, keyType), input.bindValue(values[0], valueType))
}
return result
}