当前位置: 首页>>代码示例>>Golang>>正文


Golang structs.New函数代码示例

本文整理汇总了Golang中github.com/fatih/structs.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: SubParser

// Takes the current parser and return a new parser with
// appropriate for use within a command function
func (self *ArgParser) SubParser() *ArgParser {
	parser := NewParser()
	src := structs.New(self)
	dest := structs.New(parser)

	// Copy all the public values
	for _, field := range src.Fields() {
		if field.IsExported() {
			dest.Field(field.Name()).Set(field.Value())
		}
	}

	parser.args = self.args
	parser.rules = self.rules
	parser.log = self.log
	parser.helpAdded = self.helpAdded
	parser.addHelp = self.addHelp
	parser.options = self.options
	parser.flags = self.flags

	// Remove all Commands from our rules
	for i := len(parser.rules) - 1; i >= 0; i-- {
		if parser.rules[i].HasFlag(IsCommand) {
			// Remove the rule
			parser.rules = append(parser.rules[:i], parser.rules[i+1:]...)
		}
	}
	// Clear the selected Commands
	parser.Command = nil
	parser.IsSubParser = true
	return parser
}
开发者ID:thrawn01,项目名称:args,代码行数:34,代码来源:parser.go

示例2: pathCRLRead

func (b *backend) pathCRLRead(
	req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	name := strings.ToLower(d.Get("name").(string))
	if name == "" {
		return logical.ErrorResponse(`"name" parameter must be set`), nil
	}

	b.crlUpdateMutex.RLock()
	defer b.crlUpdateMutex.RUnlock()

	var retData map[string]interface{}

	crl, ok := b.crls[name]
	if !ok {
		return logical.ErrorResponse(fmt.Sprintf(
			"no such CRL %s", name,
		)), nil
	}

	retData = structs.New(&crl).Map()

	return &logical.Response{
		Data: retData,
	}, nil
}
开发者ID:quixoten,项目名称:vault,代码行数:25,代码来源:path_crls.go

示例3: Load

// Load loads the source into the config defined by struct s
func (f *FlagLoader) Load(s interface{}) error {
	if f.FlagTagName == "" {
		f.FlagTagName = "flag"
	}

	strct := structs.New(s)
	structName := strct.Name()

	flagSet := flag.NewFlagSet(structName, flag.ExitOnError)

	for _, field := range strct.Fields() {
		f.processField(flagSet, field.Name(), field)
	}

	//flagSet.Usage no use for now, we still use other library for full command
	//line argument parsing.
	//flagSet.Usage = func() {
	//fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
	//flagSet.PrintDefaults()
	//fmt.Fprintf(os.Stderr, "\nGenerated environment variables:\n")
	//e := &EnvironmentLoader{
	//	Prefix:    f.EnvPrefix,
	//	CamelCase: f.CamelCase,
	//}
	//e.PrintEnvs(s)
	//fmt.Println("")
	//}

	args := os.Args[1:]
	if f.Args != nil {
		args = f.Args
	}

	return flagSet.Parse(args)
}
开发者ID:heartsg,项目名称:dasea,代码行数:36,代码来源:flag.go

示例4: applyConfigFile

func applyConfigFile(options *Options, filePath string) error {
	filePath = expandHomeDir(filePath)
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return err
	}

	fileString := []byte{}
	log.Printf("Loading config file at: %s", filePath)
	fileString, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	config := make(map[string]interface{})
	hcl.Decode(&config, string(fileString))
	o := structs.New(options)
	for _, name := range o.Names() {
		configName := strings.ToLower(strings.Join(camelcase.Split(name), "_"))
		if val, ok := config[configName]; ok {
			field, ok := o.FieldOk(name)
			if !ok {
				return errors.New("No such field: " + name)
			}
			err := field.Set(val)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
开发者ID:nkiraly,项目名称:gotty,代码行数:32,代码来源:app.go

示例5: pathRoleRead

// pathRoleRead is used to view the information registered for a given AMI ID.
func (b *backend) pathRoleRead(
	req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleEntry, err := b.lockedAWSRole(req.Storage, strings.ToLower(data.Get("role").(string)))
	if err != nil {
		return nil, err
	}
	if roleEntry == nil {
		return nil, nil
	}

	// Prepare the map of all the entries in the roleEntry.
	respData := structs.New(roleEntry).Map()

	// HMAC key belonging to the role should NOT be exported.
	delete(respData, "hmac_key")

	// Display the ttl in seconds.
	respData["ttl"] = roleEntry.TTL / time.Second
	// Display the max_ttl in seconds.
	respData["max_ttl"] = roleEntry.MaxTTL / time.Second

	return &logical.Response{
		Data: respData,
	}, nil
}
开发者ID:chrishoffman,项目名称:vault,代码行数:26,代码来源:path_role.go

示例6: initialize

func initialize() {
	// remove temp files
	os.RemoveAll(DBdir)

	// open db
	d, err := db.OpenDB(DBdir)

	if err != nil {
		panic(err)
	}

	// create collection
	if err := d.Create("Entries"); err != nil {
		panic(err)
	}

	// collection instance
	docEntries := d.Use("Entries")

	// dummy data
	entries := Entries{
		&Entry{1, time.Now(), "Entry 1", "First Entry!"},
		&Entry{2, time.Now(), "Golang", "Go language is awesome"},
	}

	// insert each
	for _, entry := range entries {
		docEntries.Insert(structs.New(entry).Map())
	}
}
开发者ID:jancarloviray,项目名称:go-adventures,代码行数:30,代码来源:main.go

示例7: FromRequest

func FromRequest(req *restful.Request, raw interface{}) (bson.M, error) {
	result := bson.M{}
	s := structs.New(raw)
fields:
	for _, field := range s.Fields() {
		name := field.Name()
		tags := strings.Split(field.Tag(FilterTag), ",")
		if len(tags) > 0 {
			name = tags[0] // take field name from tag
			tags = tags[1:]
		}
		bsonName := getBsonName(field)
		if bsonName == "" {
			bsonName = name
		}
		val := req.QueryParameter(name)
		if val != "" {
			if v, err := parseValue(field, val); err != nil {
				return nil, fmt.Errorf("param %s: %v", name, err)
			} else {
				result[bsonName] = v
				// if there is an eq value then we just skip modifiers
				continue fields
			}
		}
		modifiers := getModifiers(tags)
	modifiers:
		for _, m := range modifiers {
			mName := fmt.Sprintf("%s%s%s", name, ModifierDivider, m)
			val := req.QueryParameter(mName)
			if val == "" {
				continue modifiers
			}
			if m == in || m == nin {
				ins := []interface{}{}
				for _, val := range strings.Split(val, ",") {
					if val == "" {
						continue
					}
					if v, err := parseValue(field, val); err != nil {
						return nil, fmt.Errorf("param %s: %v", mName, err)
					} else {
						ins = append(ins, v)
					}
				}
				result[bsonName] = bson.M{fmt.Sprintf("$%s", m): ins}
				continue modifiers
			}
			// gt, gte, lt, lte, ne
			if v, err := parseValue(field, val); err != nil {
				return nil, fmt.Errorf("param %s: %v", name, err)
			} else {
				result[bsonName] = bson.M{fmt.Sprintf("$%s", m): v}
				// if there is an eq value then we just skip modifiers
				continue fields
			}
		}
	}
	return result, nil
}
开发者ID:iwarsong,项目名称:bearded,代码行数:60,代码来源:fltr.go

示例8: pathRoleRead

func (b *backend) pathRoleRead(
	req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	role, err := b.getRole(req.Storage, data.Get("name").(string))
	if err != nil {
		return nil, err
	}
	if role == nil {
		return nil, nil
	}

	hasMax := true
	if len(role.MaxTTL) == 0 {
		role.MaxTTL = "(system default)"
		hasMax = false
	}
	if len(role.TTL) == 0 {
		if hasMax {
			role.TTL = "(system default, capped to role max)"
		} else {
			role.TTL = "(system default)"
		}
	}

	resp := &logical.Response{
		Data: structs.New(role).Map(),
	}

	return resp, nil
}
开发者ID:jeteon,项目名称:vault,代码行数:29,代码来源:path_roles.go

示例9: GetQuery

func GetQuery(raw interface{}) bson.M {
	result := bson.M{}
	if raw == nil {
		return result
	}
	s := structs.New(raw)
	for _, field := range s.Fields() {
		if field.IsZero() {
			continue
		}
		name := field.Name()
		if tagValue := field.Tag(FilterTag); tagValue != "" {
			tags := strings.Split(tagValue, ",")
			if len(tags) > 0 {
				if tags[0] != "" {
					name = tags[0] // take field name from tag
				}
			}
		}
		bsonName := getBsonName(field)
		if bsonName == "" {
			bsonName = name
		}
		result[bsonName] = field.Value()
	}
	return result
}
开发者ID:iwarsong,项目名称:bearded,代码行数:27,代码来源:fltr.go

示例10: apiPostMessage

// this is a confusing hack that I'm using because slack's RTM websocket
// doesn't seem to support their own markup syntax. So anything that looks
// like it has markup in it is sent into this function by the write thread
// instead of into the websocket where it belongs.
func apiPostMessage(e Event) {
	Logger.Debug(`Posting through api`)
	var req = ApiRequest{
		URL:    `https://slack.com/api/chat.postMessage`,
		Values: make(url.Values),
		Broker: e.Broker,
	}
	req.Values.Set(`channel`, e.Channel)
	req.Values.Set(`text`, e.Text)
	if e.Attachments != nil {
		aJson, _ := json.Marshal(e.Attachments)
		req.Values.Set(`attachments`, string(aJson))
	}
	req.Values.Set(`id`, strconv.Itoa(int(e.ID)))
	req.Values.Set(`as_user`, e.Broker.Config.Name)
	req.Values.Set(`pretty`, `1`)
	authResp, _ := MakeAPIReq(req)
	s := structs.New(authResp) // convert this to a map[string]interface{} why not? hax.
	resp := s.Map()
	if replyVal, isReply := resp[`reply_to`]; isReply {
		if replyVal != nil {
			e.Broker.handleApiReply(resp)
		}
	}
}
开发者ID:sharadgana,项目名称:lazlo,代码行数:29,代码来源:api.go

示例11: buildStruct

func (b *Builder) buildStruct(v interface{}, obj Object, ignored ...string) {
	for _, field := range structs.New(toStruct(v)).Fields() {
		if !field.IsExported() {
			continue
		}

		key := b.keyFromField(field)
		if key == "" {
			continue
		}

		if !b.Recursive {
			b.set(obj, key, field.Value(), ignored...)
			continue
		}

		if s, ok := field.Value().(fmt.Stringer); ok && b.FlatStringers {
			if !reflect.ValueOf(s).IsNil() {
				b.set(obj, key, s.String(), ignored...)
			}
			continue
		}

		child := flatten(field.Value())
		if child == nil {
			b.set(obj, key, field.Value(), ignored...)
			continue
		}

		b.New(key).build(child, obj, ignored...)
	}
}
开发者ID:koding,项目名称:koding,代码行数:32,代码来源:object.go

示例12: where

func where(in interface{}, field string, sliceVal interface{}) ([]interface{}, error) {
	ret := make([]interface{}, 0)
	if in == nil {
		return ret, errors.New("where: source is nil")
	}
	if field == "" {
		return ret, errors.New("where: field is empty")
	}
	if sliceVal == nil {
		return ret, errors.New("where: value is nil")
	}

	if reflect.TypeOf(in).Kind() != reflect.Slice {
		return ret, errors.New("where: source is no slice value")
	}

	s := reflect.ValueOf(in)
	for i := 0; i < s.Len(); i++ {
		val := s.Index(i).Interface()
		st := structs.New(val)
		fieldVal, ok := st.FieldOk(field)
		if !ok {
			return ret, errors.Errorf("where: key %q not found", field)
		}
		if fieldVal.Value() == sliceVal {
			ret = append(ret, val)
		}
	}

	return ret, nil
}
开发者ID:denkhaus,项目名称:rancher-meta-template,代码行数:31,代码来源:funcs.go

示例13: Load

// Load loads the source into the config defined by struct s
func (f *FlagLoader) Load(s interface{}) error {
	strct := structs.New(s)
	structName := strct.Name()

	flagSet := flag.NewFlagSet(structName, flag.ExitOnError)
	f.flagSet = flagSet

	for _, field := range strct.Fields() {
		f.processField(field.Name(), field)
	}

	flagSet.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flagSet.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\nGenerated environment variables:\n")
		e := &EnvironmentLoader{
			Prefix:    f.EnvPrefix,
			CamelCase: f.CamelCase,
		}
		e.PrintEnvs(s)
		fmt.Println("")
	}

	args := os.Args[1:]
	if f.Args != nil {
		args = f.Args
	}

	return flagSet.Parse(args)
}
开发者ID:four2five,项目名称:multiconfig,代码行数:31,代码来源:flag.go

示例14: printAppDetail

func printAppDetail(a App) {
	var output []string
	var outputEnv []string
	fields := structs.New(a).Fields()

	fmt.Println("\nApplication Details:")

	for _, f := range fields {
		if f.Name() == "Addresses" {
			output = append(output, fmt.Sprintf("%s:\n", f.Name()))
			for _, v := range a.Addresses {
				output = append(output, fmt.Sprintf("……|%s", v))
			}
		} else if f.Name() == "Certificates" {
			output = append(output, fmt.Sprintf("%s:| Use \"--full\" to see certificates", f.Name()))
			output = append(output, fmt.Sprintf("– PrivateKey: |%s\n", a.Certificates["private_key"]))
		} else if f.Name() == "CreatedAt" {
			output = append(output, fmt.Sprintf("%s: | %s\n", f.Name(), utils.FormatTime(a.CreatedAt+"Z")))
		} else if f.Name() == "CurrentDeployments" {
			output = append(output, fmt.Sprintf("%s:\n", f.Name()))
			for k, v := range a.CurrentDeployments {
				output = append(output, fmt.Sprintf("……|%s: %s", k, v))
			}
		} else if f.Name() == "Environment" {
			outputEnv = append(outputEnv, fmt.Sprintf("%s:\n", f.Name()))
			for k, v := range a.Environment {
				outputEnv = append(outputEnv, fmt.Sprintf("%s=%s", k, v))
			}
		} else if f.Name() == "Location" {
			output = append(output, fmt.Sprintf("%s: |Identifier: %s\t UUID: %s\n", f.Name(), a.Location["identifier"], a.Location["uuid"]))
		} else if f.Name() == "Metadata" {
			mdata, _ := json.Marshal(a.Metadata)
			output = append(output, fmt.Sprintf("%s: |%s\n", f.Name(), mdata))
		} else if f.Name() == "Ports" {
			output = append(output, fmt.Sprintf("%s:\n", f.Name()))
			for _, v := range a.Ports {
				output = append(output, fmt.Sprintf("……|%s", v))
			}
		} else if f.Name() == "Rules" {
			output = append(output, fmt.Sprintf("%s:\n", f.Name()))
			for k, v := range a.Rules {
				output = append(output, fmt.Sprintf("……|%s=%v", k, v))
			}
		} else if f.Name() == "SSLPorts" {
			output = append(output, fmt.Sprintf("%s:\n", f.Name()))
			for _, v := range a.SSLPorts {
				output = append(output, fmt.Sprintf("……|%s", v))
			}
		} else if f.Name() == "UpdatedAt" {
			output = append(output, fmt.Sprintf("%s: | %s\n", f.Name(), utils.FormatTime(a.UpdatedAt+"Z")))
		} else {
			output = append(output, fmt.Sprintf("%s: |%v\n", f.Name(), f.Value()))
		}
	}

	fmt.Println(columnize.SimpleFormat(output))
	fmt.Println("\n")
	fmt.Println(columnize.SimpleFormat(outputEnv))
}
开发者ID:devx,项目名称:kumoru-cli,代码行数:59,代码来源:applications.go

示例15: readErrorFromData

func readErrorFromData(data interface{}) error {
	st := structs.New(data)
	if st.IsZero() {
		return nil
	}
	msgErr := st.Field("Error")
	return msgErr.Value().(error)
}
开发者ID:bosky101,项目名称:mc,代码行数:8,代码来源:console.go


注:本文中的github.com/fatih/structs.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。