Save 37% off PRO during our Black Friday Sale! »

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

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

5a2478d5008e1c64bca72c650178341e?s=128

atsushi-ishibashi

June 10, 2019
Tweet

Transcript

  1. ಠࣗϑΝΠϧܗࣜʹ StructTagͰཱͪ޲͔͏ Finatext ੴڮ ३ࢤ

  2. Finatext

  3. None
  4. None
  5. ࣗݾ঺հ - ੴڮ३ࢤ • ࡏֶதʹFinatextʹؔΘΔ • εϚʔτϓϥεͷূ݊γεςϜͷઃܭɾߏஙΛ ୲౰ • ೔ࠒ࢖͍ͬͯΔݴޠɿGoݴޠ

    • terraform-provider-awsʹͦͦ͜͜ߩݙ • झຯɿα΢φ • @bashi0501
  6. StructTag͸࢖ͬͯ·͔͢ʁ

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

    (gopkg.in/go- playground/validator.v9) Α͘࢖͏λά
  8. • ͋ΔϑΥʔϚοτͷΤϯίʔυ/ σίʔυΛָ͍ͨ͠ • ΞϊςʔγϣϯͰॲཧ಺༰Λઃఆ ͍ͨ͠ ༻్

  9. TagΛࣗ࡞ͨ͜͠ͱ͋Δਓ!

  10. ͲΜͳϑΝΠϧʁ • SHIFT_JIS • ݻఆ௕

  11. encoding/jsonύοέʔδʹ฿ͬͯ 2ͭͷؔ਺Λ࣮૷ package custom func Unmarshal(p []byte, v interface{}) error

    func Marshal(v interface{}) ([]byte, error)
  12. 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
  13. 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)) } }
  14. 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
  15. 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ͷྫ
  16. 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ͷྫ
  17. ಠࣗ࢓༷ͷϑΝΠϧ Ͱͷ࿈ܞ ಠࣗϑΥʔϚοτ Ͱͷ௨৴ ΋؆୯ʹѻ͑Δ

  18. ͍΍ɺ ͦ΋ͦ΋ಠࣗϑΥʔϚοτ͸ ࠷ޙͷखஈ$

  19. • ৭Μͳ͜ͱग़དྷͦ͏ͳؾʹͳΔ ͕ɺͦΕ͸ͨͿΜTagͰ΍Δ͜ ͱ͡Όͳ͍ • ࡞Βͳͯ͘ྑ͍ʹӽͨ͜͠ͱ͸ ͳ͍ ·ͱΊ