json - Check if a map is initialised in Golang -


i'm decoding json struct, , i'd handle case particular field not provided.

struct:

type config struct {     solrhost string     solrport int     solrcore string     servers  map[string][]int } 

json decode:

{   "solrhost": "localhost",   "solrport": 8380,   "solrcore": "testcore", } 

in method decodes json, i'd check if map[string][]int has been initialised, , if not, so.

current code:

func decodejson(input string, output *config) error {     if len(input) == 0 {         return fmt.errorf("empty string")     }     decoder := json.newdecoder(strings.newreader(input))     err := decoder.decode(output)     if err != nil {         if err != io.eof {             return err         }     }      // if output.server.isnotinitialized...      return nil } 

could make use of recover()? "nicest" way achieve task?

the zero value of map nil, check against it:

if output.servers == nil { /* ... */ } 

alternatively, can check length. handles case of empty map:

if len(output.servers) == 0 { /* ... */ } 

Comments