本文整理匯總了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
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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())
}
}
示例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
}
示例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
}
示例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
}
示例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)
}
}
}
示例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...)
}
}
示例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
}
示例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)
}
示例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))
}
示例15: readErrorFromData
func readErrorFromData(data interface{}) error {
st := structs.New(data)
if st.IsZero() {
return nil
}
msgErr := st.Field("Error")
return msgErr.Value().(error)
}