Example #1
1
// Add an import for the supplied type, without recursing.
func addImportForType(imports importMap, t reflect.Type) {
	// If there is no package path, this is a built-in type and we don't need an
	// import.
	pkgPath := t.PkgPath()
	if pkgPath == "" {
		return
	}

	// Work around a bug in Go:
	//
	//     http://code.google.com/p/go/issues/detail?id=2660
	//
	var errorPtr *error
	if t == reflect.TypeOf(errorPtr).Elem() {
		return
	}

	// Use the identifier that's part of the type's string representation as the
	// import identifier. This means that we'll do the right thing for package
	// "foo/bar" with declaration "package baz".
	match := typePackageIdentifierRegexp.FindStringSubmatch(t.String())
	if match == nil {
		return
	}

	imports[match[1]] = pkgPath
}
Example #2
0
// Since it's easy to pass the wrong method to a middleware/handler route, and since the user can't rely on static type checking since we use reflection,
// lets be super helpful about what they did and what they need to do.
// Arguments:
//  - vfn is the failed method
//  - addingType is for "You are adding {addingType} to a router...". Eg, "middleware" or "a handler" or "an error handler"
//  - yourType is for "Your {yourType} function can have...". Eg, "middleware" or "handler" or "error handler"
//  - args is like "rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc"
//    - NOTE: args can be calculated if you pass in each type. BUT, it doesn't have example argument name, so it has less copy/paste value.
func instructiveMessage(vfn reflect.Value, addingType string, yourType string, args string, ctxType reflect.Type) string {
	// Get context type without package.
	ctxString := ctxType.String()
	splitted := strings.Split(ctxString, ".")
	if len(splitted) <= 1 {
		ctxString = splitted[0]
	} else {
		ctxString = splitted[1]
	}

	str := "\n" + strings.Repeat("*", 120) + "\n"
	str += "* You are adding " + addingType + " to a router with context type '" + ctxString + "'\n"
	str += "*\n*\n"
	str += "* Your " + yourType + " function can have one of these signatures:\n"
	str += "*\n"
	str += "* // If you don't need context:\n"
	str += "* func YourFunctionName(" + args + ")\n"
	str += "*\n"
	str += "* // If you want your " + yourType + " to accept a context:\n"
	str += "* func (c *" + ctxString + ") YourFunctionName(" + args + ")  // or,\n"
	str += "* func YourFunctionName(c *" + ctxString + ", " + args + ")\n"
	str += "*\n"
	str += "* Unfortunately, your function has this signature: " + vfn.Type().String() + "\n"
	str += "*\n"
	str += strings.Repeat("*", 120) + "\n"

	return str
}
Example #3
0
// Get all the parameters setup for invocation.
func (method ApiMethod) createArguments(userId UserId, userName UserName, token Token, response http.ResponseWriter, request *http.Request) (bool, []reflect.Value) {
	var handlerType reflect.Type = reflect.TypeOf(method.handler)
	var numParams int = handlerType.NumIn()

	var apiParamIndex = 0
	var paramValues []reflect.Value = make([]reflect.Value, numParams)

	for i := 0; i < numParams; i++ {
		var ParamType reflect.Type = handlerType.In(i)

		// The user id, token, request, and response get handled specially.
		if method.auth && ParamType.String() == "goapi.Token" {
			paramValues[i] = reflect.ValueOf(token)
		} else if method.auth && ParamType.String() == "goapi.UserId" {
			paramValues[i] = reflect.ValueOf(userId)
		} else if method.auth && ParamType.String() == "goapi.UserName" {
			paramValues[i] = reflect.ValueOf(userName)
		} else if ParamType.String() == "*http.Request" {
			paramValues[i] = reflect.ValueOf(request)
		} else if ParamType.String() == "http.ResponseWriter" {
			paramValues[i] = reflect.ValueOf(response)
		} else {
			// Normal param, fetch the next api parameter and pass it along.
			ok, val := method.fetchParam(apiParamIndex, request)
			if !ok {
				return false, []reflect.Value{}
			}

			paramValues[i] = val
			apiParamIndex++
		}
	}

	return true, paramValues
}
Example #4
0
// Returns the number of bits packed
// as the second return value
func makePacker(lsb uint64, strct reflect.Type) (packer, uint64, error) {
	ptrType := strct.Kind() == reflect.Ptr
	if ptrType {
		strct = strct.Elem()
	}
	if strct.Kind() != reflect.Struct {
		return nil, 0, Error{fmt.Errorf("gopack: non-struct type %v", strct.String())}
	}
	n := strct.NumField()
	packers := make([]packer, 0)
	var bitsPacked uint64
	for i := 0; i < n; i++ {
		field := strct.Field(i)
		if isExported(field) {
			f, bits, err := makeFieldPacker(lsb, field)
			if err != nil {
				return nil, 0, err
			}
			lsb += bits
			bitsPacked += bits
			packers = append(packers, f)
		} else {
			packers = append(packers, noOpPacker)
		}
	}
	return makeCallAllPackers(packers, ptrType), bitsPacked, nil
}
Example #5
0
func (d *Decoder) decodeStruct(s *decodStatus, v reflect.Value, t reflect.Type, tg tag) error {
	switch t.String() {
	case "time.Time":
		val, ok := s.GetValue(d.env)
		if !ok {
			return nil
		}
		tf := tg.Modifiers["timeformat"]
		if tf == "" {
			tf = "2006-01-02 15:04:05"
		}
		t, err := time.Parse(tf, val)
		if err != nil {
			return err
		}
		v.Set(reflect.ValueOf(t))
	default:
		for i := 0; i < t.NumField(); i++ {
			f := t.Field(i)
			fv := v.Field(i)
			if !fv.CanSet() {
				continue
			}
			err := d.decodeElement(s, fv, f.Type, newTag(f))
			if err != nil {
				return err
			}
		}
	}
	return nil
}
Example #6
0
// Check if the inInnerType is of type struct
func (encode *encoder) ensureInInnerType(outInnerType reflect.Type) error {
	switch outInnerType.Kind() {
	case reflect.Struct:
		return nil
	}
	return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported")
}
Example #7
0
func getTypeDescribe(typ reflect.Type) *typeDescribe {
	key := typ.String()
	if td, ok := typeDescribes[key]; ok {
		return td
	}
	return createTypeDescribe(typ)
}
Example #8
0
func coerce(v interface{}, typ reflect.Type) (reflect.Value, error) {
	var err error
	if typ.Kind() == reflect.Ptr {
		return reflect.ValueOf(v), nil
	}
	switch typ.String() {
	case "string":
		v, err = coerceString(v)
	case "int", "int16", "int32", "int64":
		v, err = coerceInt64(v)
	case "uint", "uint16", "uint32", "uint64":
		v, err = coerceUint64(v)
	case "float32", "float64":
		v, err = coerceFloat64(v)
	case "bool":
		v, err = coerceBool(v)
	case "time.Duration":
		v, err = coerceDuration(v)
	case "net.Addr":
		v, err = coerceAddr(v)
	case "nsq.BackoffStrategy":
		v, err = coerceBackoffStrategy(v)
	default:
		v = nil
		err = fmt.Errorf("invalid type %s", typ.String())
	}
	return valueTypeCoerce(v, typ), err
}
Example #9
0
// MustFindParamName return param name by given reflect type.
// Panic if param name not found.
func (e *ExecutionCoordinator) MustFindParamName(typ reflect.Type) string {
	name, ok := e.paramTypeRegister.findTypeName(typ)
	if !ok {
		panic("Find Param Name Panic: " + typ.String())
	}
	return name
}
Example #10
0
func generateUid(typ reflect.Type, name string) string {
	if len(name) > 0 {
		return typ.String() + ":" + name
	} else {
		return typ.String() + ":-"
	}
}
Example #11
0
func (this *FileInfo) getAlias(packet string, fieldType reflect.Type) (string, bool) {
	stdType := true
	alias := fieldType.String()
	pktPath := fieldType.PkgPath()
	if len(pktPath) > 0 {
		stdType = false
		if fieldType.Kind() == reflect.Ptr {
			if pktPath != "" && pktPath != packet {
				if packet, found := this.Imports[pktPath]; !found {
					ref := alias
					if idx := strings.Index(ref, "."); idx >= 0 {
						ref = ref[:idx]
					}
					if _, found := this.RefImport[ref]; found {
						ref = genPacketAliasMD5(pktPath)
						alias = ref + "." + fieldType.Name()
					}
					this.RefImport[ref] = pktPath
					this.Imports[pktPath] = packet
				} else {
					alias = packet + "." + pktPath
				}
			}
		}
	}

	return alias, stdType
}
Example #12
0
func (t *TGen) decPtr(name string, val reflect.Type) {
	t.decNilBegin(name)
	t.src += name + "= new(" + TypeName(val.String(), false) + ")\n"
	t.stackName.Push("(*" + name + ")")
	t.decode(val.Elem())
	t.decNilEnd()
}
Example #13
0
// String 根据名称和类型返回相应的字符串值,返回的bool表示该值是否存在
func (this *ContextValueContainer) Contains(name string, t reflect.Type) (meta.ValueProvider, bool) {
	// 查找 web.Processor.Finders
	var finder, ok = this.Context.Processor.Finders[t.String()]
	if ok {
		ok = finder.Contains(this.Context, name, t)
	}
	if !ok {
		// 查找 web.Processor.MutiTypeFinders
		for _, f := range this.Context.Processor.MutiTypeFinders {
			if f.Contains(this.Context, name, t) {
				finder = f
				ok = true
				break
			}
		}
	}
	if ok {
		return &ContextValueProvider{
			this.Context,
			finder,
			name,
			t,
		}, true
	}
	var vc = this.Context.Processor.DefaultValueContainer
	if vc != nil {
		return vc.Contains(name, t)
	}
	return nil, false
}
Example #14
0
func newControllerInfo(namespace string, t reflect.Type, defaultAction string) *controllerInfo {
	typeName := t.String()
	if strings.HasPrefix(typeName, "*") {
		panic(errInvalidCtrlType(typeName))
	}
	numMethod := t.NumMethod()
	if numMethod < 1 {
		panic(errCtrlNoAction(typeName))
	}
	methods := make([]string, 0, numMethod)
	for i := 0; i < numMethod; i++ {
		methodInfo := t.Method(i)
		numIn := methodInfo.Type.NumIn()
		numOut := methodInfo.Type.NumOut()
		if numIn != 1 || numOut != 1 {
			continue
		}
		methodName := methodInfo.Name
		methods = append(methods, methodName)
	}
	if len(methods) < 1 {
		panic(errCtrlNoAction(typeName))
	}
	actions := make(map[string]string, len(methods))
	for _, m := range methods {
		actions[strings.ToLower(m)] = m
	}
	return &controllerInfo{
		NsName:        namespace,
		CtrlName:      getControllerName(t),
		CtrlType:      t,
		Actions:       actions,
		DefaultAction: defaultAction,
	}
}
Example #15
0
func (d mysqlDialect) CompatibleSqlTypes(f reflect.Type) []string {
	switch f.Kind() {
	case reflect.Struct:
		if f.String() == "time.Time" {
			return []string{"timestamp"}
		}
	case reflect.Bool:
		return []string{"boolean"}
	case reflect.Int, reflect.Int32, reflect.Uint, reflect.Uint32:
		return []string{"int", "integer", "bigint"}
	case reflect.Int64, reflect.Uint64:
		return []string{"bigint"}
	case reflect.Int8, reflect.Uint8:
		return []string{"tinyint", "smallint", "mediumint", "int", "integer", "bigint"}
	case reflect.Int16, reflect.Uint16:
		return []string{"mediumint", "int", "integer", "bigint"}
	case reflect.Float32:
		return []string{"double", "float"}
	case reflect.Float64:
		return []string{"double"}
	case reflect.Slice:
		if f.String() == "[]uint8" { //[]byte
			return []string{"varbinary", "longblob"}
		}
	case reflect.String:
		return []string{"varchar", "text", "longtext"}
	}
	panic("invalid sql type")
}
Example #16
0
func ptrType2SQLType(t reflect.Type) (st SQLType, has bool) {
	typeStr := t.String()
	has = true

	switch typeStr {
	case "*string":
		st = SQLType{Varchar, 255, 0}
	case "*bool":
		st = SQLType{Bool, 0, 0}
	case "*complex64", "*complex128":
		st = SQLType{Varchar, 64, 0}
	case "*float32":
		st = SQLType{Float, 0, 0}
	case "*float64":
		st = SQLType{Double, 0, 0}
	case "*int64", "*uint64":
		st = SQLType{BigInt, 0, 0}
	case "*time.Time":
		st = SQLType{DateTime, 0, 0}
	case "*int", "*int16", "*int32", "*int8", "*uint", "*uint16", "*uint32", "*uint8":
		st = SQLType{Int, 0, 0}
	default:
		has = false
	}
	return
}
Example #17
0
func newDecoder(typ reflect.Type) (typeDecoder, error) {
	switch typ.Kind() {
	case reflect.Array:
		return arrayDecoder(typ)
	case reflect.Slice:
		return sliceDecoder(typ)
	case reflect.Struct:
		return structDecoder(typ)
	case reflect.Int8, reflect.Uint8:
		return int8Decoder, nil
	case reflect.Int16, reflect.Uint16:
		return int16Decoder, nil
	case reflect.Int32, reflect.Uint32:
		return int32Decoder, nil
	case reflect.Int64, reflect.Uint64:
		return int64Decoder, nil

	case reflect.Float32:
		return float32Decoder, nil
	case reflect.Float64:
		return float64Decoder, nil

	case reflect.Complex64:
		return complex64Decoder, nil
	case reflect.Complex128:
		return complex128Decoder, nil
	}
	return nil, errors.New("can't decode type " + typ.String())
}
Example #18
0
func getComparator(dt reflect.Type) (funcPointer interface{}) {
	switch dt.Kind() {
	case reflect.Int:
		funcPointer = func(a, b int) int64 { return int64(a - b) }
	case reflect.Int8:
		funcPointer = func(a, b int8) int64 { return int64(a - b) }
	case reflect.Int16:
		funcPointer = func(a, b int16) int64 { return int64(a - b) }
	case reflect.Int32:
		funcPointer = func(a, b int32) int64 { return int64(a - b) }
	case reflect.Uint:
		funcPointer = func(a, b uint) int64 { return int64(a - b) }
	case reflect.Uint8:
		funcPointer = func(a, b uint8) int64 { return int64(a - b) }
	case reflect.Uint16:
		funcPointer = func(a, b uint16) int64 { return int64(a - b) }
	case reflect.Uint32:
		funcPointer = func(a, b uint32) int64 { return int64(a - b) }
	case reflect.Uint64:
		funcPointer = func(a, b uint64) int64 { return int64(a - b) }
	case reflect.Int64:
		funcPointer = func(a, b int64) int64 { return a - b }
	case reflect.Float32:
		funcPointer = DefaultFloat32Comparator
	case reflect.Float64:
		funcPointer = DefaultFloat64Comparator
	case reflect.String:
		funcPointer = DefaultStringComparator
	default:
		log.Panicf("No default comparator for %s:%s", dt.String(), dt.Kind().String())
	}
	return
}
Example #19
0
// getTypName returns a string representing the name of the object typ.
// if the name is defined then it is used, otherwise, the name is derived from the
// Stringer interface.
//
// the stringer returns something like *somepkg.MyStruct, so skip
// the *somepkg and return MyStruct
func getTypName(typ reflect.Type) string {
	if typ.Name() != "" {
		return typ.Name()
	}
	split := strings.Split(typ.String(), ".")
	return split[len(split)-1]
}
Example #20
0
func getOrCreateSchema(definitions Definitions, t reflect.Type) *Schema {
	var result Schema
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	if t.Kind() == reflect.Map {
		if t.Key().Kind() != reflect.String {
			panic("swagger supports only maps with string keys")
		}
		result.Type = "object"
		result.AdditionalProperties = getOrCreateSchema(definitions, t.Elem())
		return &result
	}

	if t.Kind() == reflect.Interface {
		result.Type = "object"
		return &result
	}

	result.Type = typeName(t)
	if result.Type == "object" {
		name := t.String()
		if _, ok := definitions[name]; ok {
			result = Schema{Ref: "#/definitions/" + name}
			return &result
		}
		definitions[name] = result

		if t.NumField() > 0 {
			result.Properties = Properties{}
		}
		for i := 0; i < t.NumField(); i++ {
			field := t.Field(i)
			if field.PkgPath != "" {
				continue
			}
			name := field.Tag.Get("json")
			if name == "" {
				name = field.Tag.Get("key")
				if name == "" {
					name = field.Name
				}
			}
			if field.Type.Kind() != reflect.Ptr {
				result.Required = append(result.Required, name)
			}
			fieldSchema := getOrCreateSchema(definitions, field.Type)
			fieldSchema.Description = field.Tag.Get("description")
			result.Properties[name] = fieldSchema
		}
		definitions[name] = result
		result = Schema{Ref: "#/definitions/" + name}
	} else if result.Type == "array" {
		itemsSchema := getOrCreateSchema(definitions, t.Elem())
		result.Items = &Items{*itemsSchema}
	}

	return &result
}
Example #21
0
func fixArgs(args []reflect.Value, lastParamType reflect.Type, context Context) []reflect.Value {
	if lastParamType.String() == "interface {}" ||
		lastParamType.String() == "hprose.Context" {
		args = append(args, reflect.ValueOf(context))
	}
	return args
}
Example #22
0
func sizeof(t reflect.Type) (int, error) {
	switch t.Kind() {
	case reflect.Array:
		n, err := sizeof(t.Elem())
		if err != nil {
			return 0, err
		}
		return t.Len() * n, nil

	case reflect.Struct:
		sum := 0
		for i, n := 0, t.NumField(); i < n; i++ {
			s, err := sizeof(t.Field(i).Type)
			if err != nil {
				return 0, err
			}
			sum += s
		}
		return sum, nil

	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
		reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
		return int(t.Size()), nil
	}
	return 0, errors.New("invalid type " + t.String())
}
Example #23
0
// The reflection type must have all its indirections processed out.
// typeLock must be held.
func getTypeInfo(rt reflect.Type) (*typeInfo, os.Error) {
	if _, ok := rt.(*reflect.PtrType); ok {
		panic("pointer type in getTypeInfo: " + rt.String())
	}
	info, ok := typeInfoMap[rt]
	if !ok {
		info = new(typeInfo)
		name := rt.Name()
		gt, err := getType(name, rt)
		if err != nil {
			return nil, err
		}
		info.id = gt.id()
		t := info.id.gobType()
		switch typ := rt.(type) {
		case *reflect.ArrayType:
			info.wire = &wireType{arrayT: t.(*arrayType)}
		case *reflect.MapType:
			info.wire = &wireType{mapT: t.(*mapType)}
		case *reflect.SliceType:
			// []byte == []uint8 is a special case handled separately
			if _, ok := typ.Elem().(*reflect.Uint8Type); !ok {
				info.wire = &wireType{sliceT: t.(*sliceType)}
			}
		case *reflect.StructType:
			info.wire = &wireType{structT: t.(*structType)}
		}
		typeInfoMap[rt] = info
	}
	return info, nil
}
func checkStructs(c *C, t reflect.Type, structsChecked map[string]struct{}) {
	for t.Kind() == reflect.Ptr || t.Kind() == reflect.Map || t.Kind() == reflect.Slice {
		t = t.Elem()
	}

	if t.Kind() != reflect.Struct {
		return
	}
	if _, present := structsChecked[t.String()]; present {
		// Already checked this type
		return
	}

	structsChecked[t.String()] = struct{}{}

	byUpperCase := make(map[string]int)
	for i := 0; i < t.NumField(); i++ {
		sf := t.Field(i)

		// Check that the yaml tag does not contain an _.
		yamlTag := sf.Tag.Get("yaml")
		if strings.Contains(yamlTag, "_") {
			c.Fatalf("yaml field name includes _ character: %s", yamlTag)
		}
		upper := strings.ToUpper(sf.Name)
		if _, present := byUpperCase[upper]; present {
			c.Fatalf("field name collision in configuration object: %s", sf.Name)
		}
		byUpperCase[upper] = i

		checkStructs(c, sf.Type, structsChecked)
	}
}
Example #25
0
//if not defined primary key.the first key will as primary key
func (this *simpleOrm) getPKName(t reflect.Type) (pkName string, pkIsAuto bool) {
	v, exists := this.tableMap[t.String()]
	if exists {
		return v.PkFieldName, v.PkIsAuto
	}
	return GetPKName(t)
}
Example #26
0
func (namer *TypeEventNamer) GetEventNameFromType(t reflect.Type) EventName {
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	Log.Notice("Getting name from type: %v", t.String())
	return EventName(t.PkgPath() + "/" + t.Name())
}
Example #27
0
func (b modelBuilder) keyFrom(st reflect.Type) string {
	key := st.String()
	if len(st.Name()) == 0 { // unnamed type
		// Swagger UI has special meaning for [
		key = strings.Replace(key, "[]", "||", -1)
	}
	return key
}
Example #28
0
// headers for -o wide
func formatWideHeaders(wide bool, t reflect.Type) []string {
	if wide {
		if t.String() == "*api.Pod" || t.String() == "*api.PodList" {
			return []string{"NODE"}
		}
	}
	return nil
}
Example #29
0
func (this *simpleOrm) getTableName(t reflect.Type) string {
	//todo: 用int做键
	v, exists := this.tableMap[t.String()]
	if exists {
		return v.TableName
	}
	return t.Name()
}
Example #30
0
func testRegisteredCollectionType(t *testing.T, collection *Collection, expectedName string, expectedType reflect.Type) {
	// Check that the name and type are correct
	if collection.Name() != expectedName {
		t.Errorf("Registered name was incorrect. Expected %s but got %s", expectedName, collection.Name())
	}
	if collection.spec.typ == nil {
		t.Fatalf("Registered model spec had nil type")
	}
	if collection.spec.typ != expectedType {
		t.Errorf("Registered type was incorrect. Expected %s but got %s", expectedType.String(), collection.spec.typ.String())
	}

	// Check that the model type was added to the appropriate maps
	if !testPool.nameIsRegistered(expectedName) {
		t.Error("Registered spec was not added to the modelNameToSpec map")
	}
	if !testPool.typeIsRegistered(expectedType) {
		t.Error("Registered spec was not added to the modelTypeToSpec map")
	}

	// Check the underlying spec
	spec := collection.spec
	if len(spec.fields) != 3 {
		t.Errorf("Expected spec to have 3 fields but got %d", len(spec.fields))
	}
	expectedFields := map[string]*fieldSpec{
		"Int": &fieldSpec{
			kind:      primativeField,
			name:      "Int",
			redisName: "Int",
			typ:       reflect.TypeOf(1),
			indexKind: noIndex,
		},
		"Bool": &fieldSpec{
			kind:      primativeField,
			name:      "Bool",
			redisName: "Bool",
			typ:       reflect.TypeOf(true),
			indexKind: noIndex,
		},
		"String": &fieldSpec{
			kind:      primativeField,
			name:      "String",
			redisName: "String",
			typ:       reflect.TypeOf(""),
			indexKind: noIndex,
		},
	}
	for _, expectedField := range expectedFields {
		gotField, found := spec.fieldsByName[expectedField.name]
		if !found {
			t.Errorf("Expected field with name %s but it was not in spec", expectedField.name)
		}
		if !reflect.DeepEqual(expectedField, gotField) {
			t.Errorf("Field with name %s was incorrect. Expected %+v but got %+v", expectedField.name, expectedField, gotField)
		}
	}
}