當前位置: 首頁>>代碼示例>>Golang>>正文


Golang reflections.GetField函數代碼示例

本文整理匯總了Golang中github.com/oleiade/reflections.GetField函數的典型用法代碼示例。如果您正苦於以下問題:Golang GetField函數的具體用法?Golang GetField怎麽用?Golang GetField使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了GetField函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Bind

func (r *Row) Bind(x interface{}, strategy map[string]string) error {

	for src, dest := range strategy {

		data, ok := r.data[src]

		if ok {
			k, err := reflections.GetFieldKind(x, dest)
			if err != nil {
				return err
			}

			switch k {
			case reflect.String:
				{
					reflections.SetField(x, dest, data)
				}
			case reflect.Int64:
				{
					i, err := strconv.ParseInt(data, 10, 64)
					if err != nil {
						return err
					}
					reflections.SetField(x, dest, i)
				}
			case reflect.Ptr:
				{
					value, err := reflections.GetField(x, dest)
					if err != nil {
						return err
					}
					if reflect.TypeOf(value) == typeDec {
						dec, success := new(inf.Dec).SetString(data)
						if !success {
							fmt.Errorf("Could not parse inf.Dec: %s", data)
						}
						reflections.SetField(x, dest, dec)
					}
				}
			case reflect.Struct:
				{
					value, err := reflections.GetField(x, dest)
					if err != nil {
						return err
					}
					if reflect.TypeOf(value) == typeTime {
						date, err := time.ParseInLocation("2006-01-02 15:04:05", data, r.opts.TimeZone)
						if err != nil {
							return err
						}
						reflections.SetField(x, dest, date)
					}
				}
			}
		}
	}

	return nil
}
開發者ID:relops,項目名稱:csvb,代碼行數:59,代碼來源:csvb.go

示例2: AssertObjectKeysEqual

func AssertObjectKeysEqual(t *testing.T, a, b interface{}, keys ...string) {
	assert.True(t, len(keys) > 0, "No keys provided.")
	for _, k := range keys {
		c, err := reflections.GetField(a, k)
		assert.Nil(t, err)
		d, err := reflections.GetField(b, k)
		assert.Nil(t, err)
		assert.Equal(t, c, d, "%s", k)
	}
}
開發者ID:ory-am,項目名稱:workshop-dbg,代碼行數:10,代碼來源:equalKeys.go

示例3: LoadModel

func (this *CCMomentHandler) LoadModel(moment models.CCMoment) models.Moment {
	fields, _ := reflections.Fields(&models.Moment{})
	//new instance
	momentModel := models.Moment{}

	for i := 0; i < len(fields); i++ {
		has, _ := reflections.HasField(moment, fields[i])
		if has == true {
			fmt.Println("Field Exist------", fields[i])
			if fields[i] == "Volunteer_id" {
				fmt.Println("Volunteer_id Exist------")
				var userObj CCUserHandler
				var volunteerObj CCVolunteerHandler
				var usermodel models.CCUser
				var volunteerModel models.CCVolunteer
				value, err := reflections.GetField(moment, fields[i])

				if err == nil && value != nil {
					str, _ := value.(string)

					volunteerModel, err = volunteerObj.FetchVolunteerForId(str)
					if err == nil {
						fmt.Println("volunteer Exist------", volunteerModel)
						usermodel, err = userObj.FetchUserById(volunteerModel.User_id)
						fmt.Println("User Exist------", usermodel)
						if err == nil {
							responseModel := userObj.LoadModel(usermodel)
							setError := reflections.SetField(&momentModel, fields[i], responseModel) // err != nil
							if setError != nil {
								panic(setError)
							}
						}
					}

				}
			} else {
				value, err := reflections.GetField(moment, fields[i])
				if err == nil {
					fmt.Println("Field Value------", value)
					setError := reflections.SetField(&momentModel, fields[i], value) // err != nil

					if setError != nil {
						panic(setError)
					}

				}
			}

		}

	}
	fmt.Println("Data set to Model --- ", momentModel)
	return momentModel
}
開發者ID:naikparag,項目名稱:lego,代碼行數:54,代碼來源:moment.go

示例4: GetNextPage

// GetNextPage provided a collection of resources (Builds or Jobs),
// will update the ListOptions to fetch the next resource page on next call.
func (into *ListOptions) GetNextPage(from interface{}) error {
	if reflect.TypeOf(from).Kind() != reflect.Slice {
		return fmt.Errorf("provided interface{} does not represent a slice")
	}

	slice := reflect.ValueOf(from)
	if slice.Len() == 0 {
		return fmt.Errorf("provided interface{} is a zero sized slice")
	}

	lastElem := slice.Index(slice.Len() - 1).Interface()
	has, _ := reflections.HasField(lastElem, "Number")
	if !has {
		return fmt.Errorf("last element of the provided slice does not have a Number attribute")
	}

	value, err := reflections.GetField(lastElem, "Number")
	if err != nil {
		return err
	}

	// We rely on travis sending us numbers representations here
	// so no real need to check for errors
	number, _ := strconv.ParseUint(value.(string), 10, 64)
	into.AfterNumber = uint(math.Max(float64(number), 0))

	return nil
}
開發者ID:Ableton,項目名稱:go-travis,代碼行數:30,代碼來源:travis.go

示例5: validateField

func (l Loader) validateField(fieldName string, label string, validationRules string) error {
	// Split up the validation rules
	rules := strings.Split(validationRules, ",")

	// Loop through each rule, and perform it
	for _, rule := range rules {
		if rule == "required" {
			if l.fieldValueIsEmpty(fieldName) {
				return l.Errorf("Missing %s.", label)
			}
		} else if rule == "file-exists" {
			value, _ := reflections.GetField(l.Config, fieldName)

			// Make sure the value is converted to a string
			if valueAsString, ok := value.(string); ok {
				// Return an error if the path doesn't exist
				if _, err := os.Stat(valueAsString); err != nil {
					return fmt.Errorf("Could not find %s located at %s", label, value)
				}
			}
		} else {
			return fmt.Errorf("Unknown config validation rule `%s`", rule)
		}
	}

	return nil
}
開發者ID:Jasperswaagman,項目名稱:agent,代碼行數:27,代碼來源:loader.go

示例6: LoadModel

func (this *CCUserHandler) LoadModel(user models.CCUser) models.User {
	fields, _ := reflections.Fields(&models.User{})
	//new instance
	userModel := models.User{}

	for i := 0; i < len(fields); i++ {
		has, _ := reflections.HasField(user, fields[i])
		if has == true {
			fmt.Println("Field Exist------", fields[i])

			value, err := reflections.GetField(user, fields[i])
			if err == nil {
				fmt.Println("Field Value------", value)
				setError := reflections.SetField(&userModel, fields[i], value) // err != nil

				if setError != nil {
					panic(setError)
				}

			}

		}

	}
	fmt.Println("Data set to Model --- ", userModel)
	return userModel
}
開發者ID:naikparag,項目名稱:lego,代碼行數:27,代碼來源:user.go

示例7: sendGenericQuery

func (bot TgBot) sendGenericQuery(path string, ignore string, file string, payload interface{}) ResultWithMessage {
	url := bot.buildPath(path)
	switch val := payload.(type) {
	//WebHook
	case SetWebhookQuery:
		return bot.genericSendPostData(url, val)
	case SetWebhookCertQuery:
		return bot.sendConvertingFile(url, ignore, file, val)
	// ID
	case SendPhotoIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendAudioIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendVoiceIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendDocumentIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendStickerIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
	case SendVideoIDQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.genericSendPostData(url, val)
		// Path
	case SendPhotoPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendAudioPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendVoicePathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendDocumentPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendStickerPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	case SendVideoPathQuery:
		hookPayload(&val, bot.DefaultOptions)
		return bot.sendConvertingFile(url, ignore, file, val)
	default:
		ipath, err := reflections.GetField(val, ignore)
		if err != nil {
			break
		}
		params := convertInterfaceMap(val, []string{ignore})
		return bot.uploadFileWithResult(url, params, file, ipath)
	}
	errc := 400
	errs := "Wrong Query!"
	return ResultWithMessage{ResultBase{false, &errc, &errs}, nil}
}
開發者ID:joseluiscd,項目名稱:go-tgbot,代碼行數:58,代碼來源:tgbot-netcalls.go

示例8: HandleGlobalFlags

func HandleGlobalFlags(cfg interface{}) {
	// Enable debugging if a Debug option is present
	debug, err := reflections.GetField(cfg, "Debug")
	if debug == true && err == nil {
		logger.SetLevel(logger.DEBUG)
	}

	// Enable HTTP debugging
	debugHTTP, err := reflections.GetField(cfg, "DebugHTTP")
	if debugHTTP == true && err == nil {
		agent.APIClientEnableHTTPDebug()
	}

	// Turn off color if a NoColor option is present
	noColor, err := reflections.GetField(cfg, "NoColor")
	if noColor == true && err == nil {
		logger.SetColors(false)
	}
}
開發者ID:Jasperswaagman,項目名稱:agent,代碼行數:19,代碼來源:global.go

示例9: LoadModel

func (this *CCEventHandler) LoadModel(event models.CCEvent) models.Event {
	fields, _ := reflections.Fields(&models.Event{})
	//new instance
	eventModel := models.Event{}

	for i := 0; i < len(fields); i++ {
		has, _ := reflections.HasField(event, fields[i])
		if has == true {
			fmt.Println("Field Exist------", fields[i])
			if fields[i] == "Created_by" {
				var userObj CCUserHandler
				var usermodel models.CCUser
				value, err := reflections.GetField(event, fields[i])

				if err == nil && value != nil {
					str, _ := value.(string)
					usermodel, err = userObj.FetchUserById(str)
					if err == nil {
						responseModel := userObj.LoadModel(usermodel)
						setError := reflections.SetField(&eventModel, fields[i], responseModel) // err != nil
						if setError != nil {
							panic(setError)
						}
					}
				}
			} else {
				value, err := reflections.GetField(event, fields[i])
				if err == nil {
					fmt.Println("Field Value------", value)
					setError := reflections.SetField(&eventModel, fields[i], value) // err != nil

					if setError != nil {
						panic(setError)
					}
				}
			}

		}

	}
	fmt.Println("Data set to Model --- ", eventModel)
	return eventModel
}
開發者ID:naikparag,項目名稱:lego,代碼行數:43,代碼來源:event.go

示例10: GetValueByNamespace

func (t *MyTools) GetValueByNamespace(object interface{}, ns []string) interface{} {
	// current level of namespace
	current := ns[0]
	fields, err := reflections.Fields(object)
	if err != nil {
		fmt.Printf("Could not return fields for object{%v}\n", object)
		return nil
	}

	for _, field := range fields {
		tag, err := reflections.GetFieldTag(object, field, "json")
		if err != nil {
			fmt.Printf("Could not find tag for field{%s}\n", field)
			return nil
		}
		// remove omitempty from tag
		tag = strings.Replace(tag, ",omitempty", "", -1)
		if tag == current {
			val, _ := reflections.GetField(object, field)

			// handling of special cases for slice and map
			switch reflect.TypeOf(val).Kind() {
			case reflect.Slice:
				idx, _ := strconv.Atoi(ns[1])
				val := reflect.ValueOf(val)
				if val.Index(idx).Kind() == reflect.Struct {
					return t.GetValueByNamespace(val.Index(idx).Interface(), ns[2:])
				} else {
					return val.Index(idx).Interface()
				}
			case reflect.Map:
				key := ns[1]
				// try uint64 map (memory_stats case)
				if vi, ok := val.(map[string]uint64); ok {
					return vi[key]
				}
				// try with hugetlb map (hugetlb_stats case)
				val := reflect.ValueOf(val)
				kval := reflect.ValueOf(key)
				if reflect.TypeOf(val.MapIndex(kval).Interface()).Kind() == reflect.Struct {
					return t.GetValueByNamespace(val.MapIndex(kval).Interface(), ns[2:])
				}
			default:
				// last ns, return value found
				if len(ns) == 1 {
					return val
				} else {
					// or go deeper
					return t.GetValueByNamespace(val, ns[1:])
				}
			}
		}
	}
	return nil
}
開發者ID:sandlbn,項目名稱:snap-plugin-collector-docker,代碼行數:55,代碼來源:tools.go

示例11: sendConvertingFile

func (bot TgBot) sendConvertingFile(url string, ignore string, file string, val interface{}) ResultWithMessage {
	ipath, err := reflections.GetField(val, ignore)
	if err != nil {
		errc := 400
		errs := "Wrong Query!"
		return ResultWithMessage{ResultBase{false, &errc, &errs}, nil}
	}
	fpath := fmt.Sprintf("%+v", ipath)
	params := convertInterfaceMap(val, []string{ignore})
	return bot.uploadFileWithResult(url, params, file, fpath)
}
開發者ID:joseluiscd,項目名稱:go-tgbot,代碼行數:11,代碼來源:tgbot-netcalls.go

示例12: PopulateHoursByDays

func (D *DayOfWeekCalls) PopulateHoursByDays(results []HourByDaysRecord) {
	for i := 0; i < len(results); i++ {
		hourName := fmt.Sprintf("H%d", i)

		dayName := fmt.Sprintf("Day%d", D.DayOfWeek-1)

		valueHour, _ := reflections.GetField(D.SummaryCallsPerHours, hourName)

		_ = reflections.SetField(&results[i], dayName, valueHour)
	}
}
開發者ID:vassilux,項目名稱:revor,代碼行數:11,代碼來源:callsByHours.go

示例13: hookDisableWebpage

func hookDisableWebpage(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "DisableWebPagePreview")
		if has {
			value, _ := reflections.GetField(payload, "DisableWebPagePreview")
			bvalue := value.(*bool)
			if bvalue == nil {
				reflections.SetField(payload, "DisableWebPagePreview", nv)
			}
		}
	}
}
開發者ID:joseluiscd,項目名稱:go-tgbot,代碼行數:12,代碼來源:tgbot-defaultoptions.go

示例14: hookReplyToMessageID

func hookReplyToMessageID(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "ReplyToMessageID")
		if has {
			value, _ := reflections.GetField(payload, "ReplyToMessageID")
			bvalue := value.(*int)
			if bvalue == nil {
				reflections.SetField(payload, "ReplyToMessageID", nv)
			}
		}
	}
}
開發者ID:joseluiscd,項目名稱:go-tgbot,代碼行數:12,代碼來源:tgbot-defaultoptions.go

示例15: hookOneTimeKeyboard

func hookOneTimeKeyboard(payload interface{}, nv *bool) {
	if nv != nil {
		has, _ := reflections.HasField(payload, "OneTimeKeyboard")
		if has {
			value, _ := reflections.GetField(payload, "OneTimeKeyboard")
			bvalue := value.(*bool)
			if bvalue == nil {
				reflections.SetField(payload, "OneTimeKeyboard", nv)
			}
		}
	}
}
開發者ID:joseluiscd,項目名稱:go-tgbot,代碼行數:12,代碼來源:tgbot-defaultoptions.go


注:本文中的github.com/oleiade/reflections.GetField函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。