github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/fields/00_typeswitch/parse.go (about)

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