Upgrade to Pro — share decks privately, control downloads, hide ads and more …

独自ファイル形式にStructTagで立ち向かう

 独自ファイル形式にStructTagで立ち向かう

atsushi-ishibashi

June 10, 2019
Tweet

More Decks by atsushi-ishibashi

Other Decks in Technology

Transcript

  1. • json, xml • form, query • db • validate

    (gopkg.in/go- playground/validator.v9) Α͘࢖͏λά
  2. func Unmarshal(p []byte, v interface{}) error { //reflect.Value tt :=

    reflect.ValueOf(v) // reflect.Kind // ૊ΈࠐΈܕ,Ptr,Interface,StructͳͲͷܕΛද͢enum if tt.Kind() != reflect.Ptr { return error } // PtrͷnilνΣοΫ if tt.IsNil() { return error } // Elem returns the value that interface contains or that pointer points to elem := tt.Elem() fmt.Println(elem.Kind()) // struct … Unmarshal
  3. func Unmarshal(p []byte, v interface{}) error { … elem :=

    tt.Elem() //reflect.Type // t := elem.Type() //֤fieldʹରͯ͠ॲཧΛ͍ͯ͘͠ for i := 0; i < t.NumField(); i++ { //reflect.StructField //Field໊΍ܕɺTagͳͲͷ৘ใΛࢀরͰ͖Δ field := t.Field(i) fmt.Println(field.Name) //field໊ fmt.Println(field.Type.Kind()) //reflect.Kindͱͯ͠ͷܕ fmt.Println(field.Type.Name()) //typeએݴΛࣝผ͍ͨ͠ͱ͖ tag, ok := field.Tag.Lookup(“tagName”) //͋ͱ͸tagΛύʔεͯ͠p []byte͔Β͏·͍͜ͱσʔλऔ͖ͬͯͯ elem.Field(i).SetXXX(foo(p)) } }
  4. func Marshal(v interface{}) ([]byte, error) { tt := reflect.ValueOf(v) switch

    rv.Kind() { case reflect.Ptr, reflect.Interface: if rv.IsNil() { return nil, error } tt = tt.Elem() case reflect.Struct: default: return nil, error } t := tt.Type() for i := 0; i < t.NumField(); i++ { field := rt.Field(i) tag, ok := field.Tag.Lookup(“tagName”) // do something ttf := tt.Field(i) switch ttf.Kind() { case reflect.String: stringValue := ttf.String() // ग़ྗ͢Δ[]byteʹରͯ͠ૢ࡞ Marshal
  5. type Hoge struct { ID string `custom:”1,5”` // 1byte໨͔Β5byte෼ Count

    int64 `custom:”6,2”` IsFlag bool `custom:"8,1"` Price float64 `custom:"9,5"` Abs uint64 `custom:"14,3"` } p := []byte(`abcde101002.3543`) var hoge Hoge Unmarshal(p, &hoge) hoge.ID // abcde hoge.Count // 10 hoge.IsFlag // true hoge.Price // 2.3 hoge.Abs // 543 Unmarshalͷྫ
  6. type Hoge struct { ID string `custom:”1,5"` Count int64 `custom:”6,2”`

    IsFlag bool `custom:"8,1"` Price float64 `custom:"9,5"` Abs uint64 `custom:"14,3"` } hoge := Hoge{ ID: “abcde”, Count: “10”, IsFlag: true, Price: 2.3, Abs: 543, } p, err := Marshal(hoge) fmt.Println(string(p)) // abcde101002.3543 Marshalͷྫ