Last active
April 17, 2017 08:07
-
-
Save piaoger/7ab8c37e4aa439f8a1b77662ab275ed4 to your computer and use it in GitHub Desktop.
marshal and unmarshal of json/toml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"bytes" | |
"encoding/json" | |
"errors" | |
"fmt" | |
"github.com/BurntSushi/toml" | |
"errors" | |
) | |
// borrowed from golang playgroud: | |
// https://play.golang.org/p/Kd7TRoRG5w | |
func JsonMapToStruct(input map[string]interface{}, val interface{}) error { | |
tmp, err := json.Marshal(input) | |
if err != nil { | |
errmsg := fmt.Sprintf("json marshal failure: %s", err) | |
return errors.New(errmsg) | |
} | |
err = json.Unmarshal(tmp, val) | |
if err != nil { | |
errmsg := fmt.Sprintf("json unmarshal failure: %s", err) | |
return errors.New(errmsg) | |
} | |
return nil | |
} | |
func TomlMapToStruct(input map[string]interface{}, outputs interface{}) error { | |
var buf bytes.Buffer | |
encoder := toml.NewEncoder(&buf) | |
err := encoder.Encode(input) | |
if err != nil { | |
errmsg := fmt.Sprintf("toml encode toml failure: %s", err) | |
return errors.New(errmsg) | |
} | |
if _, err := toml.Decode(buf.String(), outputs); err != nil { | |
errmsg := fmt.Sprintf("toml decode toml failure: %s", err) | |
return errors.New(errmsg) | |
} | |
return nil | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment