本文整理汇总了Golang中reflect.StructTag函数的典型用法代码示例。如果您正苦于以下问题:Golang StructTag函数的具体用法?Golang StructTag怎么用?Golang StructTag使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了StructTag函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: writeStruct
func (en *Encoder) writeStruct(spec *ast.StructType, name string) {
for _, field := range spec.Fields.List {
tag := reflect.StructTag("")
if field.Tag != nil {
tag = reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1])
}
var c string
if tag.Get("if") != "" && tag.Get("noreplace") != "true" {
c = strings.Replace(tag.Get("if"), ".", name+".", -1)
}
if c != "" {
fmt.Fprintf(en.buf, "if %s {\n", c)
}
for _, n := range field.Names {
en.writeType(field.Type, fmt.Sprintf("%s.%s", name, n), tag)
}
if c != "" {
fmt.Fprint(en.buf, "}\n")
}
}
}
示例2: writeStruct
func (w *writing) writeStruct(spec *ast.StructType, name string) {
var lastCondition conditions
for _, field := range spec.Fields.List {
tag := reflect.StructTag("")
if field.Tag != nil {
tag = reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1])
}
var condition conditions
if ifTag := tag.Get("if"); ifTag != "" {
condition = parseCondition(ifTag)
}
if !lastCondition.equals(condition) {
if lastCondition != nil {
w.buf.WriteString("}\n")
}
if condition != nil {
condition.print(name, &w.buf)
}
}
lastCondition = condition
for _, n := range field.Names {
w.writeType(field.Type, fmt.Sprintf("%s.%s", name, n), tag)
}
}
if lastCondition != nil {
w.buf.WriteString("}\n")
}
}
示例3: checkCanonicalFieldTag
// checkCanonicalFieldTag checks a single struct field tag.
func checkCanonicalFieldTag(f *File, field *ast.Field, seen *map[[2]string]token.Pos) {
if field.Tag == nil {
return
}
tag, err := strconv.Unquote(field.Tag.Value)
if err != nil {
f.Badf(field.Pos(), "unable to read struct tag %s", field.Tag.Value)
return
}
if err := validateStructTag(tag); err != nil {
raw, _ := strconv.Unquote(field.Tag.Value) // field.Tag.Value is known to be a quoted string
f.Badf(field.Pos(), "struct field tag %#q not compatible with reflect.StructTag.Get: %s", raw, err)
}
for _, key := range checkTagDups {
val := reflect.StructTag(tag).Get(key)
if val == "" || val == "-" || val[0] == ',' {
continue
}
if i := strings.Index(val, ","); i >= 0 {
val = val[:i]
}
if *seen == nil {
*seen = map[[2]string]token.Pos{}
}
if pos, ok := (*seen)[[2]string{key, val}]; ok {
f.Badf(field.Pos(), "struct field %s repeats %s tag %q also at %s", field.Names[0].Name, key, val, f.loc(pos))
} else {
(*seen)[[2]string{key, val}] = field.Pos()
}
}
// Check for use of json or xml tags with unexported fields.
// Embedded struct. Nothing to do for now, but that
// may change, depending on what happens with issue 7363.
if len(field.Names) == 0 {
return
}
if field.Names[0].IsExported() {
return
}
for _, enc := range [...]string{"json", "xml"} {
if reflect.StructTag(tag).Get(enc) != "" {
f.Badf(field.Pos(), "struct field %s has %s tag but is not exported", field.Names[0].Name, enc)
return
}
}
}
示例4: typeSchema
func typeSchema(title string, t reflect.Type, tag reflect.StructTag) *Value {
fieldType := fieldType(t, tag)
isReadOnly := tag.Get("readOnly") != ""
value := &Value{
Title: title,
Type: fieldType,
Required: isRequired(tag),
Enum: enum(tag),
Description: tag.Get("description"),
Format: Format(tag.Get("format")),
ReadOnly: isReadOnly,
}
switch fieldType {
case Map:
value.Title = t.Name()
value.Format = "tabs"
// map items
value.Items = &Value{
Type: Object,
HeaderTemplate: "{{self.key}}",
Properties: map[string]*Value{
"key": typeSchema("key", t.Key(), reflect.StructTag("")),
"value": typeSchema("value", t.Elem(), reflect.StructTag("")),
},
}
// the enum annotation for maps is for the key not for the map itself
value.Items.Properties["key"].Enum = enum(tag)
value.Enum = make([]string, 0)
// if there is valueEnum then the value is considered enum
if tag.Get("valueEnum") != "" {
value.Items.Properties["value"].Enum = strings.Split(tag.Get("valueEnum"), ",")
} else {
value.Items.Properties["value"].Enum = make([]string, 0)
}
case Array:
value.Items = typeSchema(t.Name(), t.Elem(), tag)
value.Items.HeaderTemplate = tag.Get("headerTemplate")
case ProtoEnum:
value.Enum = getProtoEnumValues(t)
case Object:
value = structSchema(title, t, tag)
}
return value
}
示例5: Apply
func (this Injector) Apply(target interface{}) {
elem := reflect.ValueOf(target)
for elem.Kind() == reflect.Ptr {
elem = elem.Elem()
}
//fmt.Println(elem, elem.Kind())
if elem.Kind() != reflect.Struct {
return
}
//fmt.Println(elem, elem.NumField())
t := elem.Type()
fieldTagMap := make(map[reflect.StructTag]string)
for i := 0; i < elem.NumField(); i++ {
structField := t.Field(i)
//fmt.Println(elem.Field(i).CanSet())
if elem.Field(i).CanSet() {
fieldTagMap[structField.Tag] = structField.Name
}
}
for key, value := range this.valueMap {
for k, v := range fieldTagMap {
if k == reflect.StructTag(key) {
elem.FieldByName(v).Set(reflect.ValueOf(value))
break
}
}
}
}
示例6: toTable
func toTable(typeInfo *genbase.TypeInfo) (*Table, error) {
table := new(Table)
table.PackageName = typeInfo.FileInfo.Name.Name
comment := typeInfo.AnnotatedComment.Text
tableName := strings.TrimPrefix(comment, "//+table: ")
table.Name = tableName
table.StructName = typeInfo.Name()
structType, err := typeInfo.StructType()
if err != nil {
return nil, err
}
fieldInfos := structType.FieldInfos()
for _, fieldInfo := range fieldInfos {
tagText := fieldInfo.Tag.Value[1 : len(fieldInfo.Tag.Value)-1]
tag := reflect.StructTag(tagText)
columnInfo := tag.Get("db")
columnMaps := strings.Split(columnInfo, ",")
columnName := columnMaps[0]
isPk := false
for _, cm := range columnMaps {
if cm == "primarykey" {
isPk = true
break
}
}
column := Column{FieldInfo: fieldInfo, Name: columnName, IsPk: isPk}
table.AddColumn(column)
}
return table, nil
}
示例7: getFlag
func getFlag(field reflect.StructField) (ths flagSpec) {
ftlen := len(field.Tag)
if ftlen > 0 && string(field.Tag[ftlen-1]) == "!" {
if ftlen > 1 && string(field.Tag[ftlen-2]) != "\\" {
field.Tag = field.Tag[:ftlen-1]
ths.imperitive = true
} else if ftlen > 2 {
field.Tag = reflect.StructTag(string(field.Tag[:len(field.Tag)-2]) + "!")
} else {
ths.imperitive = true
}
}
parts := strings.Split(string(field.Tag), ";")
switch useName := true; len(parts) {
case 3:
useName = false
ths.names = strings.Split(parts[2], ",")
fallthrough
case 2:
ths.deflt = parts[1]
fallthrough
case 1:
ths.usage = parts[0]
fallthrough
case 0:
ths.typ = field.Type
if useName {
ths.names = append(ths.names, strings.ToLower(field.Name))
}
default:
panic("Too many fields!")
}
return
}
示例8: NewResource
// Creates a new resource
// Receives the object to be mappen in a new Resource
// and receive the field name and field tag as optional arguments
func NewResource(object interface{}, args ...string) *Resource {
value := reflect.ValueOf(object)
name := value.Type().Name()
tag := ""
// Defining a name as an opitional secound argument
if len(args) >= 1 {
name = args[0]
}
// Defining a tag as an opitional thrid argument
if len(args) >= 2 {
tag = args[1]
}
field := reflect.StructField{
Name: name,
Tag: reflect.StructTag(tag),
Anonymous: false,
}
//log.Printf("field: %#v\n", field)
return scanStruct(value, field, nil)
}
示例9: hasOptionalTag
// hasOptionalTag returns true if the member has +optional in its comments or
// omitempty in its json tags.
func hasOptionalTag(m *types.Member) bool {
hasOptionalCommentTag := types.ExtractCommentTags(
"+", m.CommentLines)[tagOptional] != nil
hasOptionalJsonTag := strings.Contains(
reflect.StructTag(m.Tags).Get("json"), "omitempty")
return hasOptionalCommentTag || hasOptionalJsonTag
}
示例10: buildValue
func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error {
value = elemOf(value)
if !value.IsValid() { // no need to handle zero values
return nil
} else if tag.Get("location") != "" { // don't handle non-body location values
return nil
}
t := tag.Get("type")
if t == "" {
switch value.Kind() {
case reflect.Struct:
t = "structure"
case reflect.Slice:
t = "list"
case reflect.Map:
t = "map"
}
}
switch t {
case "structure":
if field, ok := value.Type().FieldByName("SDKShapeTraits"); ok {
tag = tag + reflect.StructTag(" ") + field.Tag
}
return b.buildStruct(value, current, tag)
case "list":
return b.buildList(value, current, tag)
case "map":
return b.buildMap(value, current, tag)
default:
return b.buildScalar(value, current, tag)
}
}
示例11: registerService
//Takes a value of a struct representing a service.
func registerService(root string, h interface{}) {
if _, ok := h.(GoRestService); !ok {
panic(ERROR_INVALID_INTERFACE)
}
t := reflect.TypeOf(h)
if t.Kind() == reflect.Ptr {
t = t.Elem()
} else {
panic(ERROR_INVALID_INTERFACE)
}
if t.Kind() == reflect.Struct {
if field, found := t.FieldByName("RestService"); found {
temp := strings.Join(strings.Fields(string(field.Tag)), " ")
meta := prepServiceMetaData(root, reflect.StructTag(temp), h, t.Name())
tFullName := _manager().addType(t.PkgPath()+"/"+t.Name(), meta)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
mapFieldsToMethods(t, f, tFullName, meta.root)
}
}
return
}
panic(ERROR_INVALID_INTERFACE)
}
示例12: AddField
func (si *StructInfo) AddField(field *ast.Field) error {
if field.Names == nil || len(field.Names) != 1 {
return errors.New(fmt.Sprintf("Field contains no name: %v", field))
}
jsonName := field.Names[0].Name
opts := tagOptions("")
if field.Tag != nil {
var tagName string
// the Tag.Value contains wrapping `` which we slice off here. We hope.
v := tagRe.ReplaceAllString(field.Tag.Value, "$1")
tag := reflect.StructTag(v).Get("json")
tagName, opts = parseTag(tag)
if tagName != "" {
jsonName = tagName
}
}
si.Fields = append(si.Fields, StructField{
Name: field.Names[0].Name,
JsonName: jsonName,
OmitEmpty: opts.Contains("omitempty"),
ForceString: opts.Contains("string"),
})
return nil
}
示例13: ExtractArgs
// ExtractArgs parses the arguments out of a template invocation, using
// the invoking fields tags.
func ExtractArgs(ctx *Context, stp *ast.StructType, name string) ([]string, error) {
var found *ast.Field
for _, f := range stp.Fields.List {
fname, err := nameFromFieldType(ctx, f.Type)
if err != nil {
return nil, err
}
if name == fname {
found = f
}
}
if found == nil {
return nil, errors.New("Couldn't find template invocation: " + name)
}
if found.Tag == nil {
return nil, nil
}
tag := reflect.StructTag(found.Tag.Value[1 : len(found.Tag.Value)-1])
return strings.Split(tag.Get("template"), ","), nil
}
示例14: parseStruct
func parseStruct(fset *token.FileSet, s *ast.StructType) *Struct {
parsedStruct := &Struct{}
if s.Fields.List != nil {
parsedStruct.Fields = make([]StructField, 0, len(s.Fields.List))
}
for _, field := range s.Fields.List {
parsedField := StructField{}
for i, name := range field.Names {
parsedField.Name += name.Name
if i != len(field.Names)-1 {
parsedField.Name += ", "
}
}
parsedField.Doc = parseComments(field.Doc)
parsedField.Comments = parseComments(field.Comment)
if field.Tag != nil {
raw := field.Tag.Value
parsedField.RawTag = raw
if len(raw) >= 2 {
// Strip leading/trailing back-ticks:
parsedField.Tag = reflect.StructTag(raw[1 : len(raw)-1])
}
}
parsedField.Type = formatTypeExpr(fset, field.Type)
parsedField.StructType = parseEmbeddedStructType(fset, field.Type)
parsedStruct.Fields = append(parsedStruct.Fields, parsedField)
}
return parsedStruct
}
示例15: getJsonTags
func getJsonTags(m *types.Member) []string {
jsonTag := reflect.StructTag(m.Tags).Get("json")
if jsonTag == "" {
return []string{}
}
return strings.Split(jsonTag, ",")
}