Go:StructTags
Go 언어의 struct tag 문법에 대한 설명.
About
위와 같이 백틱(`)으로 감싸진 부분은 Go 언어의 struct tag입니다.
Struct tag는 구조체 필드에 메타데이터를 추가하는 문법으로, 주로 직렬화/역직렬화(serialization/deserialization) 과정에서 필드 매핑을 지정할 때 사용됩니다.
읽는 방법
Go에서 struct tag는 리플렉션(reflection)을 사용하여 런타임에 읽을 수 있습니다.
package main
import (
"fmt"
"reflect"
)
type User struct {
ID int `json:"id" db:"user_id" validate:"required"`
Name string `json:"name,omitempty"`
Email string `json:"email"`
}
func main() {
user := User{}
// Get type information / 타입 정보 가져오기
t := reflect.TypeOf(user)
// Iterate through fields / 필드들을 순회
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("Field: %s\n", field.Name)
// Get entire tag string / 전체 태그 문자열 가져오기
fmt.Printf(" Full Tag: %s\n", field.Tag)
// Get specific tag value / 특정 태그 값 가져오기
jsonTag := field.Tag.Get("json")
dbTag := field.Tag.Get("db")
validateTag := field.Tag.Get("validate")
fmt.Printf(" json: %s\n", jsonTag)
fmt.Printf(" db: %s\n", dbTag)
fmt.Printf(" validate: %s\n", validateTag)
fmt.Println()
}
}
다음과 같이 출력됩니다:
Field: ID
Full Tag: json:"id" db:"user_id" validate:"required"
json: id
db: user_id
validate: required
Field: Name
Full Tag: json:"name,omitempty"
json: name,omitempty
db:
validate:
Field: Email
Full Tag: json:"email"
json: email
db:
validate:
Lookup 메서드 사용
// Check if tag exists / 태그 존재 여부 확인
func checkTag() {
user := User{}
t := reflect.TypeOf(user)
field, _ := t.FieldByName("ID")
// Lookup returns value and boolean / Lookup은 값과 boolean을 반환
if value, ok := field.Tag.Lookup("json"); ok {
fmt.Printf("json tag exists: %s\n", value)
} else {
fmt.Println("json tag not found")
}
}
Well-known struct tags
List of well-known struct tags
| Tag | Documentation |
| asn1 | |
| bigquery | |
| bson | |
| cue | |
| datastore | |
| db | |
| dynamodbav | https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/#Marshal |
| egg | |
| feature | |
| gorm | |
| graphql | |
| json | |
| mapstructure | |
| parser | |
| properties | https://pkg.go.dev/github.com/magiconair/properties#Properties.Decode |
| protobuf | |
| reform | |
| spanner | |
| toml | |
| url | |
| validate | |
| xml | |
| yaml |