-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtagParsing.go
38 lines (34 loc) · 857 Bytes
/
tagParsing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package bencoding
import (
"reflect"
"regexp"
)
func tagForFieldNamed(value reflect.Value, name string) string {
field, hasField := value.Type().FieldByName(name)
if !hasField {
return ""
}
return string(field.Tag)
}
func parseTag(tag string) *string {
const fieldRegexp = `bencoding:"([\w- ]*)"`
reg := regexp.MustCompile(fieldRegexp)
if matches := reg.FindStringSubmatch(tag); len(matches) > 2 {
panic("regexp for parsing fields seems to be wrong -- more then two groups returned")
} else if len(matches) == 2 {
return &matches[1]
} else {
return nil
}
}
func extractFieldOptions(v reflect.Value, name string) string {
tag := tagForFieldNamed(v, name)
bencodingTag := parseTag(tag)
if bencodingTag == nil {
return name
} else if *bencodingTag == "" || *bencodingTag == "-" {
return ""
} else {
return *bencodingTag
}
}