github.com/astaxie/beego@v1.12.3/context/param/conv.go (about)

     1  package param
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  
     7  	beecontext "github.com/astaxie/beego/context"
     8  	"github.com/astaxie/beego/logs"
     9  )
    10  
    11  // ConvertParams converts http method params to values that will be passed to the method controller as arguments
    12  func ConvertParams(methodParams []*MethodParam, methodType reflect.Type, ctx *beecontext.Context) (result []reflect.Value) {
    13  	result = make([]reflect.Value, 0, len(methodParams))
    14  	for i := 0; i < len(methodParams); i++ {
    15  		reflectValue := convertParam(methodParams[i], methodType.In(i), ctx)
    16  		result = append(result, reflectValue)
    17  	}
    18  	return
    19  }
    20  
    21  func convertParam(param *MethodParam, paramType reflect.Type, ctx *beecontext.Context) (result reflect.Value) {
    22  	paramValue := getParamValue(param, ctx)
    23  	if paramValue == "" {
    24  		if param.required {
    25  			ctx.Abort(400, fmt.Sprintf("Missing parameter %s", param.name))
    26  		} else {
    27  			paramValue = param.defaultValue
    28  		}
    29  	}
    30  
    31  	reflectValue, err := parseValue(param, paramValue, paramType)
    32  	if err != nil {
    33  		logs.Debug(fmt.Sprintf("Error converting param %s to type %s. Value: %v, Error: %s", param.name, paramType, paramValue, err))
    34  		ctx.Abort(400, fmt.Sprintf("Invalid parameter %s. Can not convert %v to type %s", param.name, paramValue, paramType))
    35  	}
    36  
    37  	return reflectValue
    38  }
    39  
    40  func getParamValue(param *MethodParam, ctx *beecontext.Context) string {
    41  	switch param.in {
    42  	case body:
    43  		return string(ctx.Input.RequestBody)
    44  	case header:
    45  		return ctx.Input.Header(param.name)
    46  	case path:
    47  		return ctx.Input.Query(":" + param.name)
    48  	default:
    49  		return ctx.Input.Query(param.name)
    50  	}
    51  }
    52  
    53  func parseValue(param *MethodParam, paramValue string, paramType reflect.Type) (result reflect.Value, err error) {
    54  	if paramValue == "" {
    55  		return reflect.Zero(paramType), nil
    56  	}
    57  	parser := getParser(param, paramType)
    58  	value, err := parser.parse(paramValue, paramType)
    59  	if err != nil {
    60  		return result, err
    61  	}
    62  
    63  	return safeConvert(reflect.ValueOf(value), paramType)
    64  }
    65  
    66  func safeConvert(value reflect.Value, t reflect.Type) (result reflect.Value, err error) {
    67  	defer func() {
    68  		if r := recover(); r != nil {
    69  			var ok bool
    70  			err, ok = r.(error)
    71  			if !ok {
    72  				err = fmt.Errorf("%v", r)
    73  			}
    74  		}
    75  	}()
    76  	result = value.Convert(t)
    77  	return
    78  }