Golang TypeOf示例

说明

golang typeof示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: reflect

示例#1
文件: encode_test.go 项目: rasky/go-xdr

// testExpectedMRet is a convenience method to test an expected number of bytes
// written and error for a marshal.
func testExpectedMRet(t *testing.T, name string, n, wantN int, err, wantErr error) bool {
	// First ensure the number of bytes written is the expected value.  The
	// bytes read should be accurate even when an error occurs.
	if n != wantN {
		t.Errorf("%s: unexpected num bytes written - got: %v want: %v\n",
			name, n, wantN)
		return false
	}

	// Next check for the expected error.
	if reflect.TypeOf(err) != reflect.TypeOf(wantErr) {
		t.Errorf("%s: failed to detect error - got: %v <%[2]T> want: %T",
			name, err, wantErr)
		return false
	}
	if rerr, ok := err.(*MarshalError); ok {
		if werr, ok := wantErr.(*MarshalError); ok {
			if rerr.ErrorCode != werr.ErrorCode {
				t.Errorf("%s: failed to detect error code - "+
					"got: %v want: %v", name,
					rerr.ErrorCode, werr.ErrorCode)
				return false
			}
		}
	}

	return true
}

示例#2
文件: caste.go 项目: BenoitHanotte/shorturls

// ToIntSliceE casts an empty interface to a []int.
func ToIntSliceE(i interface{}) ([]int, error) {
	jww.DEBUG.Println("ToIntSliceE called on type:", reflect.TypeOf(i))

	if i == nil {
		return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
	}

	switch v := i.(type) {
	case []int:
		return v, nil
	}

	kind := reflect.TypeOf(i).Kind()
	switch kind {
	case reflect.Slice, reflect.Array:
		s := reflect.ValueOf(i)
		a := make([]int, s.Len())
		for j := 0; j < s.Len(); j++ {
			val, err := ToIntE(s.Index(j).Interface())
			if err != nil {
				return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
			}
			a[j] = val
		}
		return a, nil
	default:
		return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
	}
}

示例#3
文件: message.go 项目: nishanths/gae

func init() {
	mt := reflect.TypeOf(mail.Message{})
	ot := reflect.TypeOf(Message{})
	if mt.NumField() != ot.NumField() {
		panic(fmt.Errorf("mismatched number of fields %s v %s", mt, ot))
	}

	for i := 0; i < mt.NumField(); i++ {
		mf := mt.Field(i)
		of := mt.Field(i)
		if mf.Name != of.Name {
			panic(fmt.Errorf("mismatched names %s v %s", mf.Name, of.Name))
		}
		if mf.Name == "Attachments" {
			if !mf.Type.Elem().ConvertibleTo(of.Type.Elem()) {
				panic(fmt.Errorf("mismatched element type for Attachments %s v %s",
					mf.Type, of.Type))
			}
		} else {
			if mf.Type != of.Type {
				panic(fmt.Errorf("mismatched type for field %s: %s v %s", mf.Name, mf.Type, of.Type))
			}
		}
	}
}

示例#4
文件: request.go 项目: newestindustry/go-form

// ParseUrlValues parses url.Values into the s interface using
// the reflect package. It also checks for the form struct tags
// so they can be used as fieldnames instead of the variable
// names. It returns the error if parsing failed.
func ParseUrlValues(query url.Values, s interface{}) error {
	fieldIndex := []int{0}
	numElements := reflect.TypeOf(s).Elem().NumField()
	for i := 0; i < numElements; i++ {
		fieldIndex[0] = i
		f := reflect.TypeOf(s).Elem().FieldByIndex(fieldIndex)
		v := reflect.ValueOf(s).Elem().FieldByIndex(fieldIndex)

		fieldname := f.Tag.Get("form")
		if fieldname == "" {
			fieldname = strings.ToLower(f.Name)
		}

		if val, ok := query[fieldname]; ok {
			curVal := val[0]
			switch v.Kind() {
			case reflect.Bool:
				castBool, _ := strconv.ParseBool(curVal)
				v.SetBool(castBool)
			case reflect.Float64:
				castFloat, _ := strconv.ParseFloat(curVal, 64)
				v.SetFloat(castFloat)
			case reflect.Int64:
				castInt, _ := strconv.ParseInt(curVal, 0, 64)
				v.SetInt(castInt)
			case reflect.String:
				v.SetString(curVal)
			default:
			}
		}
	}
	return nil
}

示例#5
文件: extensions.go 项目: 7imon7ays/bubblz

// SetExtension sets the specified extension of pb to the specified value.
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
	epb, ok := extendable(pb)
	if !ok {
		return errors.New("proto: not an extendable proto")
	}
	if err := checkExtensionTypes(epb, extension); err != nil {
		return err
	}
	typ := reflect.TypeOf(extension.ExtensionType)
	if typ != reflect.TypeOf(value) {
		return errors.New("proto: bad extension value type")
	}
	// nil extension values need to be caught early, because the
	// encoder can't distinguish an ErrNil due to a nil extension
	// from an ErrNil due to a missing field. Extensions are
	// always optional, so the encoder would just swallow the error
	// and drop all the extensions from the encoded message.
	if reflect.ValueOf(value).IsNil() {
		return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
	}

	extmap := epb.extensionsWrite()
	extmap[extension.Field] = Extension{desc: extension, value: value}
	return nil
}

示例#6
文件: describe.go 项目: duncanfinney/kubernetes

// DescribeObject implements ObjectDescriber and will attempt to print the provided object to a string,
// if at least one describer function has been registered with the exact types passed, or if any
// describer can print the exact object in its first argument (the remainder will be provided empty
// values). If no function registered with Add can satisfy the passed objects, an ErrNoDescriber will
// be returned
// TODO: reorder and partial match extra.
func (d *Describers) DescribeObject(exact interface{}, extra ...interface{}) (string, error) {
	exactType := reflect.TypeOf(exact)
	fns, ok := d.searchFns[exactType]
	if !ok {
		return "", newErrNoDescriber(exactType)
	}
	if len(extra) == 0 {
		for _, typeFn := range fns {
			if len(typeFn.Extra) == 0 {
				return typeFn.Describe(exact, extra...)
			}
		}
		typeFn := fns[0]
		for _, t := range typeFn.Extra {
			v := reflect.New(t).Elem()
			extra = append(extra, v.Interface())
		}
		return fns[0].Describe(exact, extra...)
	}

	types := []reflect.Type{}
	for _, obj := range extra {
		types = append(types, reflect.TypeOf(obj))
	}
	for _, typeFn := range fns {
		if typeFn.Matches(types) {
			return typeFn.Describe(exact, extra...)
		}
	}
	return "", newErrNoDescriber(append([]reflect.Type{exactType}, types...)...)
}

示例#7
文件: serialization_test.go 项目: xiaohui/kubernetes

func roundTrip(t *testing.T, codec runtime.Codec, item runtime.Object) {
	//t.Logf("codec: %#v", codec)

	printer := spew.ConfigState{DisableMethods: true}

	name := reflect.TypeOf(item).Elem().Name()
	data, err := runtime.Encode(codec, item)
	if err != nil {
		t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", item))
		return
	}

	obj2, err := runtime.Decode(codec, data)
	if err != nil {
		t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), printer.Sprintf("%#v", item))
		return
	}
	if !api.Semantic.DeepEqual(item, obj2) {
		t.Errorf("\n1: %v: diff: %v\nCodec: %v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, diff.ObjectGoPrintDiff(item, obj2), codec, printer.Sprintf("%#v", item), string(data), printer.Sprintf("%#v", obj2))
		return
	}

	obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object)
	if err := runtime.DecodeInto(codec, data, obj3); err != nil {
		t.Errorf("2: %v: %v", name, err)
		return
	}
	if !api.Semantic.DeepEqual(item, obj3) {
		t.Errorf("3: %v: diff: %v\nCodec: %v", name, diff.ObjectDiff(item, obj3), codec)
		return
	}
}

示例#8
文件: channel.go 项目: gcnonato/amqp

// Performs a request/response call for when the message is not NoWait and is
// specified as Synchronous.
func (me *Channel) call(req message, res ...message) error {
	if err := me.send(me, req); err != nil {
		return err
	}

	if req.wait() {
		select {
		case e := <-me.errors:
			return e

		case msg := <-me.rpc:
			if msg != nil {
				for _, try := range res {
					if reflect.TypeOf(msg) == reflect.TypeOf(try) {
						// *res = *msg
						vres := reflect.ValueOf(try).Elem()
						vmsg := reflect.ValueOf(msg).Elem()
						vres.Set(vmsg)
						return nil
					}
				}
				return ErrCommandInvalid
			} else {
				// RPC channel has been closed without an error, likely due to a hard
				// error on the Connection.  This indicates we have already been
				// shutdown and if were waiting, will have returned from the errors chan.
				return ErrClosed
			}
		}
	}

	return nil
}

示例#9
文件: coerce.go 项目: rwcarlsen/ql

func coerce(a, b interface{}) (x, y interface{}) {
	if reflect.TypeOf(a) == reflect.TypeOf(b) {
		return a, b
	}

	switch a.(type) {
	case idealComplex, idealFloat, idealInt, idealRune, idealUint:
		switch b.(type) {
		case idealComplex, idealFloat, idealInt, idealRune, idealUint:
			x, y = coerce1(a, b), b
			if reflect.TypeOf(x) == reflect.TypeOf(y) {
				return
			}

			return a, coerce1(b, a)
		default:
			return coerce1(a, b), b
		}
	default:
		switch b.(type) {
		case idealComplex, idealFloat, idealInt, idealRune, idealUint:
			return a, coerce1(b, a)
		default:
			return a, b
		}
	}
}

示例#10
文件: datum.go 项目: petermattis/cockroach

// Temporary workaround for #3633, allowing comparisons between
// heterogeneous types.
// TODO(andreimatei) Remove when type inference improves.
func mixedTypeCompare(l, r Datum) (int, bool) {
	lType := reflect.TypeOf(l)
	rType := reflect.TypeOf(r)

	// Check equality.
	eqOp, ok := CmpOps[CmpArgs{EQ, lType, rType}]
	if !ok {
		return 0, false
	}
	eq, err := eqOp.fn(EvalContext{}, l, r)
	if err != nil {
		panic(err)
	}
	if eq {
		return 0, true
	}

	// Check less than.
	ltOp, ok := CmpOps[CmpArgs{LT, lType, rType}]
	if !ok {
		return 0, false
	}
	lt, err := ltOp.fn(EvalContext{}, l, r)
	if err != nil {
		panic(err)
	}
	if lt {
		return -1, true
	}
	return 1, true
}

示例#11
文件: validation.go 项目: Alpa-vantage/fishhub

//experimenting with trying to match the field with the passed in struct
func (v *Validation) getKeyForField(passedField interface{}) string {
	typObj := reflect.TypeOf(v.Obj)
	valObj := reflect.ValueOf(v.Obj)

	typField := reflect.TypeOf(passedField)
	valField := reflect.ValueOf(passedField)

	//if our struct is a pointer, dereference it
	if typObj.Kind() == reflect.Ptr {
		typObj = typObj.Elem()
		valObj = valObj.Elem()
	}

	//if our passed in field is a pointer, dereference it
	if typField.Kind() == reflect.Ptr {
		typField = typField.Elem()
		valField = valField.Elem()
	}

	for i := 0; i < typObj.NumField(); i++ {
		field := typObj.Field(i)
		fieldValue := valObj.Field(i).Interface()
		passedValue := valField.Interface()
		if passedValue == fieldValue {
			return field.Tag.Get(v.keyTag)
		}
	}
	return ""
}

示例#12
文件: packetError_test.go 项目: SabatierBoris/go-SLP

func TestVersionToto(t *testing.T) {
	var datas = []struct {
		data   []byte
		result error
	}{
		{[]byte{0xFF}, &VersionError{}},
		{[]byte{0x02}, &VersionError{}},
		{[]byte{}, &ReadError{}},
		{[]byte{0x01}, &ReadError{}},
		{[]byte{0x01, 0xFF, 0x00, 0x0D, 0x00, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00}, &FunctionError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0D, 0x00, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00}, &ReadError{}},
		{[]byte{0x01, 0x01, 0x00, 0x0D, 0x00, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00}, &FunctionError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x02, 0x00, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &FlagError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x00, 0x01, 'e', 'n', 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &DialectError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &LanguageError{}},
		{[]byte{0x01, 0x05, 0x00, 0x0E, 0x00, 0x00, 'z', 'z', 0x00, 0x03, 0x00, 0x00, 0x00, 0x00}, &LanguageError{}},
	}

	for _, infos := range datas {
		buf := bytes.NewReader(infos.data)
		p, err := GetPacket(buf)
		if err == nil {
			t.Errorf("Test failed, expected an error, got:  '%v'", p)
		}
		if reflect.TypeOf(err) != reflect.TypeOf(infos.result) {
			t.Errorf("Test failed, expected an %s, got:  '%s'", reflect.TypeOf(infos.result), err)
		}
		t.Logf("Got the error %s", err)
	}
}

示例#13
文件: link.go 项目: NodePrime/open-mininet

// NewLink(n1, n2, [link1 properties, link2 properties])
// property which isn't specified will be generated
func NewLink(left, right Node, refs ...Link) Pair {
	result := Pair{}

	switch len(refs) {
	case 1:
		result = Pair{Left: refs[0], Right: Link{}}
	case 2:
		result = Pair{Left: refs[0], Right: refs[1]}
	default:
		break
	}

	if reflect.TypeOf(left).Elem() == reflect.TypeOf(right).Elem() && reflect.TypeOf(left).Elem() == reflect.TypeOf(Switch{}) {
		result.Left = result.Left.SetNodeName(left).SetName(left, "pp").SetPatch()
		result.Right = result.Right.SetNodeName(right).SetName(right, "pp").SetPatch()
	} else {
		result.Left = result.Left.SetCidr().SetHwAddr().
			SetNetNs(left).SetName(right, "eth").SetNodeName(left).SetState("DOWN").SetRoute()

		result.Right = result.Right.SetCidr().SetHwAddr().
			SetNetNs(right).SetName(right, "eth").SetNodeName(right).SetState("DOWN").SetRoute()
	}

	result.Left = result.Left.SetPeer(result.Right)
	result.Right = result.Right.SetPeer(result.Left)

	return result
}

示例#14
文件: net.go 项目: jerchung/completion

func init() {
	if err := content.RegisterType("net_paths", reflect.TypeOf([]string{})); err != nil {
		panic(err)
	} else if err := content.RegisterType("net_assemblies", reflect.TypeOf([]string{})); err != nil {
		panic(err)
	}
}

示例#15
文件: interface.go 项目: SimyungYang/go-study

func main() {
	file, err := os.OpenFile(
		"text01.txt",
		os.O_CREATE|os.O_RDWR|os.O_TRUNC, // 파일이 없으면 생성,
		// 읽기/쓰기, 파일을 연 뒤 내용 삭제
		os.FileMode(0644), // 파일 권한은 644
	)

	fmt.Println(reflect.TypeOf(file))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close() // main 함수가 끝나기 직전에 파일을 닫음

	w := bufio.NewWriter(file) // io.Writer 인터페이스를 따르는 file로
	// io.Writer 인터페이스를 따르는 쓰기 인스턴스 w 생성

	fmt.Println(reflect.TypeOf(w))

	w.WriteString("Hello, world!") // 쓰기 인스턴스로 버퍼에 Hello, world! 쓰기
	w.Flush()                      // 버퍼의 내용을 파일에 저장

	r := bufio.NewReader(file) // io.Reader 인터페이스를 따르는 file로
	// io.Reader 인터페이스를 따르는 읽기 인스턴스 r 생성
	fi, _ := file.Stat()         // 파일 정보 구하기
	b := make([]byte, fi.Size()) // 파일 크기만큼 바이트 슬라이스 생성

	file.Seek(0, os.SEEK_SET) // 파일 읽기 위치를 파일의 맨 처음(0)으로 이동
	r.Read(b)                 // 읽기 인스턴스로 파일의 내용을 읽어서 b에 저장

	fmt.Println(string(b)) // 문자열로 변환하여 b의 내용 출력
}

示例#16
文件: rpc2xml.go 项目: kzjeef/gorilla-xmlrpc

func RPC2XML(value interface{}) (string, error) {
	out := "<value>"
	switch reflect.ValueOf(value).Kind() {
	case reflect.Int:
		out += fmt.Sprintf("<int>%d</int>", value.(int))
	case reflect.Float64:
		out += fmt.Sprintf("<double>%f</double>", value.(float64))
	case reflect.String:
		out += String2XML(value.(string))
	case reflect.Bool:
		out += Bool2XML(value.(bool))
	case reflect.Struct:
		if reflect.TypeOf(value).String() != "time.Time" {
			out += Struct2XML(value)
		} else {
			out += Time2XML(value.(time.Time))
		}
	case reflect.Slice, reflect.Array:
		// FIXME: is it the best way to recognize '[]byte'?
		if reflect.TypeOf(value).String() != "[]uint8" {
			out += Array2XML(value)
		} else {
			out += Base642XML(value.([]byte))
		}
	case reflect.Ptr:
		if reflect.ValueOf(value).IsNil() {
			out += "<nil/>"
		}
	}
	out += "</value>"
	return out, nil
}

示例#17
文件: util.go 项目: roblillack/mars

// Equal is a helper for comparing value equality, following these rules:
//  - Values with equivalent types are compared with reflect.DeepEqual
//  - int, uint, and float values are compared without regard to the type width.
//    for example, Equal(int32(5), int64(5)) == true
//  - strings and byte slices are converted to strings before comparison.
//  - else, return false.
func Equal(a, b interface{}) bool {
	if reflect.TypeOf(a) == reflect.TypeOf(b) {
		return reflect.DeepEqual(a, b)
	}
	switch a.(type) {
	case int, int8, int16, int32, int64:
		switch b.(type) {
		case int, int8, int16, int32, int64:
			return reflect.ValueOf(a).Int() == reflect.ValueOf(b).Int()
		}
	case uint, uint8, uint16, uint32, uint64:
		switch b.(type) {
		case uint, uint8, uint16, uint32, uint64:
			return reflect.ValueOf(a).Uint() == reflect.ValueOf(b).Uint()
		}
	case float32, float64:
		switch b.(type) {
		case float32, float64:
			return reflect.ValueOf(a).Float() == reflect.ValueOf(b).Float()
		}
	case string:
		switch b.(type) {
		case []byte:
			return a.(string) == string(b.([]byte))
		}
	case []byte:
		switch b.(type) {
		case string:
			return b.(string) == string(a.([]byte))
		}
	}
	return false
}

示例#18
文件: gocheck.go 项目: evaluation-alex/gosync

func (c *C) logValue(label string, value interface{}) {
	if label == "" {
		if hasStringOrError(value) {
			c.logf("... %#v (%q)", value, value)
		} else {
			c.logf("... %#v", value)
		}
	} else if value == nil {
		c.logf("... %s = nil", label)
	} else {
		if hasStringOrError(value) {
			fv := fmt.Sprintf("%#v", value)
			qv := fmt.Sprintf("%q", value)
			if fv != qv {
				c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv)
				return
			}
		}
		if s, ok := value.(string); ok && isMultiLine(s) {
			c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value))
			c.logMultiLine(s)
		} else {
			c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value)
		}
	}
}

示例#19
文件: reflect_test.go 项目: jsp282/tendermint

func TestAnimalInterface(t *testing.T) {
	var foo Animal

	// Type of pointer to Animal
	rt := reflect.TypeOf(&foo)
	fmt.Printf("rt: %v\n", rt)

	// Type of Animal itself.
	// NOTE: normally this is acquired through other means
	// like introspecting on method signatures, or struct fields.
	rte := rt.Elem()
	fmt.Printf("rte: %v\n", rte)

	// Get a new pointer to the interface
	// NOTE: calling .Interface() is to get the actual value,
	// instead of reflection values.
	ptr := reflect.New(rte).Interface()
	fmt.Printf("ptr: %v", ptr)

	// Make a binary byteslice that represents a *snake.
	foo = Snake([]byte("snake"))
	snakeBytes := BinaryBytes(foo)
	snakeReader := bytes.NewReader(snakeBytes)

	// Now you can read it.
	n, err := new(int64), new(error)
	it := ReadBinary(foo, snakeReader, n, err).(Animal)
	fmt.Println(it, reflect.TypeOf(it))
}

示例#20
文件: scheme_test.go 项目: TencentSA/kubernetes-0.5

func runTest(t *testing.T, source interface{}) {
	name := reflect.TypeOf(source).Elem().Name()
	TestObjectFuzzer.Fuzz(source)

	s := GetTestScheme()
	data, err := s.EncodeToVersion(source, "v1")
	if err != nil {
		t.Errorf("%v: %v (%#v)", name, err, source)
		return
	}
	obj2, err := s.Decode(data)
	if err != nil {
		t.Errorf("%v: %v (%v)", name, err, string(data))
		return
	}
	if !reflect.DeepEqual(source, obj2) {
		t.Errorf("1: %v: diff: %v", name, objDiff(source, obj2))
		return
	}
	obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface()
	err = s.DecodeInto(data, obj3)
	if err != nil {
		t.Errorf("2: %v: %v", name, err)
		return
	}
	if !reflect.DeepEqual(source, obj3) {
		t.Errorf("3: %v: diff: %v", name, objDiff(source, obj3))
		return
	}
}

示例#21
文件: connection.go 项目: lud4ik/amqp

func (me *Connection) call(req message, res ...message) error {
	// Special case for when the protocol header frame is sent insted of a
	// request method
	if req != nil {
		if err := me.send(&methodFrame{ChannelId: 0, Method: req}); err != nil {
			return err
		}
	}

	select {
	case err := <-me.errors:
		if err == nil {
			return ErrClosed
		}
		return err

	case msg := <-me.rpc:
		// Try to match one of the result types
		for _, try := range res {
			if reflect.TypeOf(msg) == reflect.TypeOf(try) {
				// *res = *msg
				vres := reflect.ValueOf(try).Elem()
				vmsg := reflect.ValueOf(msg).Elem()
				vres.Set(vmsg)
				return nil
			}
		}
		return ErrCommandInvalid
	}

	panic("unreachable")
}

示例#22
文件: statement.go 项目: matm/gobuild

// Generate "where id = ? " statment or for composite key "where key1 = ? and key2 = ?"
func (statement *Statement) Id(id interface{}) *Statement {

	idValue := reflect.ValueOf(id)
	idType := reflect.TypeOf(idValue.Interface())

	switch idType {
	case reflect.TypeOf(&PK{}):
		if pkPtr, ok := (id).(*PK); ok {
			statement.IdParam = pkPtr
		}
	case reflect.TypeOf(PK{}):
		if pk, ok := (id).(PK); ok {
			statement.IdParam = &pk
		}
	default:
		// TODO treat as int primitve for now, need to handle type check
		statement.IdParam = &PK{id}

		// !nashtsai! REVIEW although it will be user's mistake if called Id() twice with
		// different value and Id should be PK's field name, however, at this stage probably
		// can't tell which table is gonna be used
		// if statement.WhereStr == "" {
		//     statement.WhereStr = "(id)=?"
		//     statement.Params = []interface{}{id}
		// } else {
		//     // TODO what if id param has already passed
		//     statement.WhereStr = statement.WhereStr + " AND (id)=?"
		//     statement.Params = append(statement.Params, id)
		// }
	}

	// !nashtsai! perhaps no need to validate pk values' type just let sql complaint happen

	return statement
}

示例#23
文件: client.go 项目: appuri/amazon-ecs-agent

// CreateRequestMessage creates the request json message using the given input.
// Note, the input *MUST* be a pointer to a valid backend type that this
// client recognises.
func (cs *ClientServerImpl) CreateRequestMessage(input interface{}) ([]byte, error) {
	msg := &RequestMessage{}

	recognizedTypes := cs.GetRecognizedTypes()
	for typeStr, typeVal := range recognizedTypes {
		if reflect.TypeOf(input) == reflect.PtrTo(typeVal) {
			msg.Type = typeStr
			break
		}
	}
	if msg.Type == "" {
		return nil, &UnrecognizedWSRequestType{reflect.TypeOf(input).String()}
	}
	messageData, err := jsonutil.BuildJSON(input)
	if err != nil {
		return nil, &NotMarshallableWSRequest{msg.Type, err}
	}
	msg.Message = json.RawMessage(messageData)

	send, err := json.Marshal(msg)
	if err != nil {
		return nil, &NotMarshallableWSRequest{msg.Type, err}
	}
	return send, nil
}

示例#24
文件: generate.go 项目: torfuzx/gocassa

func stringTypeOf(i interface{}) (string, error) {
	_, isByteSlice := i.([]byte)
	if !isByteSlice {
		// Check if we found a higher kinded type
		switch reflect.ValueOf(i).Kind() {
		case reflect.Slice:
			elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface()
			ct := cassaType(elemVal)
			if ct == gocql.TypeCustom {
				return "", fmt.Errorf("Unsupported type %T", i)
			}
			return fmt.Sprintf("list<%v>", ct), nil
		case reflect.Map:
			keyVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Key())).Interface()
			elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface()
			keyCt := cassaType(keyVal)
			elemCt := cassaType(elemVal)
			if keyCt == gocql.TypeCustom || elemCt == gocql.TypeCustom {
				return "", fmt.Errorf("Unsupported map key or value type %T", i)
			}
			return fmt.Sprintf("map<%v, %v>", keyCt, elemCt), nil
		}
	}
	ct := cassaType(i)
	if ct == gocql.TypeCustom {
		return "", fmt.Errorf("Unsupported type %T", i)
	}
	return cassaTypeToString(ct)
}

示例#25
文件: webbrowser_test.go 项目: bryanl/webbrowser

func Test_detectBrowsers(t *testing.T) {
	cases := []struct {
		o string
		t interface{}
		e error
	}{
		{o: "linux", t: &LinuxOpener{}, e: nil},
		{o: "darwin", t: &OSXOpener{}, e: nil},
		{o: "windows", t: &WindowsOpener{}, e: nil},
		{o: "freebsd", e: &UnsupportedOSError{}},
	}

	for _, c := range cases {
		o, err := detectBrowsers(c.o)

		got := reflect.TypeOf(err)
		want := reflect.TypeOf(c.e)
		if got != want {
			t.Fatalf("detectBrowsers() err = %v; want = %v", err, c.e)
		}

		if err == nil {
			got := reflect.TypeOf(o)
			want := reflect.TypeOf(c.t)
			if got != want {
				t.Errorf("detectBrowsers() type = %v; want = %v", got, want)
			}
		}
	}

}

示例#26
文件: workerconnection.go 项目: JeremyOT/gototo

func CreateConverter(i interface{}, wrappedInResponse bool, convertTypeDecoderConfig *DecoderConfig, convertTypeTagName string) ConverterFunction {
	typ := reflect.TypeOf(i)
	if typ.Kind() != reflect.Ptr {
		log.Panicf("Only pointers to structs may be registered as a response type: %#v", typ)
	}
	customUnpack := typ.Implements(reflect.TypeOf((*Unpacker)(nil)).Elem())
	typ = typ.Elem()
	if typ.Kind() != reflect.Struct {
		log.Panicf("Only pointers to structs may be registered as a response type: %#v", typ)
	}
	converter := func(input interface{}) (output interface{}, err error) {
		if wrappedInResponse {
			responseValue, err := ConvertValue(responseType, input, false, convertTypeDecoderConfig, convertTypeTagName)
			if err != nil {
				return nil, err
			}
			parsedResponse := responseValue.Interface().(*Response)
			if !parsedResponse.Success {
				return nil, &ResponseError{text: parsedResponse.Error, code: parsedResponse.ErrorCode}
			}
			input = parsedResponse.Result
		}
		inputValue, err := ConvertValue(typ, input, customUnpack, convertTypeDecoderConfig, convertTypeTagName)
		if err != nil {
			return
		}
		output = inputValue.Interface()
		return
	}
	return converter
}

示例#27
文件: dbconf_test.go 项目: abourget/goose

func TestDriverSetFromEnvironmentVariable(t *testing.T) {

	databaseUrlEnvVariableKey := "DB_DRIVER"
	databaseUrlEnvVariableVal := "sqlite3"
	databaseOpenStringKey := "DATABASE_URL"
	databaseOpenStringVal := "db.db"

	os.Setenv(databaseUrlEnvVariableKey, databaseUrlEnvVariableVal)
	os.Setenv(databaseOpenStringKey, databaseOpenStringVal)

	dbconf, err := NewDBConf("../../_example", "environment_variable_config", "")
	if err != nil {
		t.Fatal(err)
	}

	got := reflect.TypeOf(dbconf.Driver.Dialect)
	want := reflect.TypeOf(&Sqlite3Dialect{})

	if got != want {
		t.Errorf("Not able to read the driver type from environment variable."+
			"got %v want %v", got, want)
	}

	gotOpenString := dbconf.Driver.OpenStr
	wantOpenString := databaseOpenStringVal

	if gotOpenString != wantOpenString {
		t.Errorf("Not able to read the open string from the environment."+
			"got %v want %v", gotOpenString, wantOpenString)
	}
}

示例#28
文件: table.go 项目: matm/gobuild

// default sql type change to go types
func SQLType2Type(st SQLType) reflect.Type {
	name := strings.ToUpper(st.Name)
	switch name {
	case Bit, TinyInt, SmallInt, MediumInt, Int, Integer, Serial:
		return reflect.TypeOf(1)
	case BigInt, BigSerial:
		return reflect.TypeOf(int64(1))
	case Float, Real:
		return reflect.TypeOf(float32(1))
	case Double:
		return reflect.TypeOf(float64(1))
	case Char, Varchar, TinyText, Text, MediumText, LongText:
		return reflect.TypeOf("")
	case TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary:
		return reflect.TypeOf([]byte{})
	case Bool:
		return reflect.TypeOf(true)
	case DateTime, Date, Time, TimeStamp, TimeStampz:
		return reflect.TypeOf(c_TIME_DEFAULT)
	case Decimal, Numeric:
		return reflect.TypeOf("")
	default:
		return reflect.TypeOf("")
	}
}

示例#29
文件: protocol.go 项目: SeaSunOpenSource/go-jxhttp

func init() {
	typmap = make(map[string]reflect.Type)
	typmap["VerifySessionResp"] = reflect.TypeOf(VerifySessionResp{})
	typmap["VerifySessionReq"] = reflect.TypeOf(VerifySessionReq{})
	typmap["PayNtf"] = reflect.TypeOf(PayNtf{})
	typmap["PayRsp"] = reflect.TypeOf(PayRsp{})
}

示例#30
文件: exec.go 项目: bmatsuo/go-spec

func (t *SpecTest) satisfy(x, fn interface{}) (satisfies bool, err error) {
	t.doDebug(func() { t.Logf("%#v satisfies function %#v", x, fn) })
	switch x.(type) {
	case FnCall:
		x = x.(FnCall).out[0].Interface()
	default:
	}

	fnval := reflect.ValueOf(fn)

	// Check the type of fn (fn(x)bool).
	if k := fnval.Kind(); k != reflect.Func {
		return false, errors.New("Satisfy given non-function")
	}
	if typ := fnval.Type(); typ.NumIn() != 1 {
		return false, errors.New("Satisfy needs a function of one argument")
	} else if xtyp := reflect.TypeOf(x); !xtyp.AssignableTo(typ.In(0)) {
		return false, errors.New("Satisfy argument type-mismatch")
	} else if typ.NumOut() != 1 {
		return false, errors.New("Satisfy needs a predicate (func(x) bool)")
	} else if !typ.Out(0).AssignableTo(reflect.TypeOf(satisfies)) {
		return false, errors.New("Satisfy output type-mismatch")
	}
	fnout := fnval.Call([]reflect.Value{reflect.ValueOf(x)})
	satisfies = fnout[0].Interface().(bool)
	return
}

展开阅读全文