github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/fields/01_typemap/parse.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "errors" 6 "io" 7 ) 8 9 func ParseFields(r io.Reader) (map[string]Field, error) { 10 var config struct { 11 Fields []struct { 12 Name string 13 Type string 14 Val interface{} 15 Multiplier interface{} 16 } 17 } 18 19 err := json.NewDecoder(r).Decode(&config) 20 if err != nil { 21 return nil, err 22 } 23 24 fields := map[string]Field{} 25 26 for _, jsonField := range config.Fields { 27 val, valok := jsonField.Val.(float64) 28 if !valok { 29 return nil, errors.New("unsupported type " + jsonField.Type) 30 } 31 32 var field Field 33 switch jsonField.Type { 34 case "uint": 35 field = &Uint{ 36 ID: jsonField.Name, 37 Value: uint64(val), 38 } 39 case "float": 40 field = &Float{ 41 ID: jsonField.Name, 42 Value: float64(val), 43 } 44 default: 45 return nil, errors.New("unsupported type " + jsonField.Type) 46 } 47 48 fields[field.Name()] = field 49 } 50 51 return fields, nil 52 }