Skip to content

Instantly share code, notes, and snippets.

@piaoger
Last active April 17, 2017 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piaoger/7ab8c37e4aa439f8a1b77662ab275ed4 to your computer and use it in GitHub Desktop.
Save piaoger/7ab8c37e4aa439f8a1b77662ab275ed4 to your computer and use it in GitHub Desktop.
marshal and unmarshal of json/toml
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