codec.go (765B)
1 package hcl 2 3 import ( 4 "bytes" 5 "encoding/json" 6 7 "github.com/hashicorp/hcl" 8 "github.com/hashicorp/hcl/hcl/printer" 9 ) 10 11 // Codec implements the encoding.Encoder and encoding.Decoder interfaces for HCL encoding. 12 // TODO: add printer config to the codec? 13 type Codec struct{} 14 15 func (Codec) Encode(v map[string]interface{}) ([]byte, error) { 16 b, err := json.Marshal(v) 17 if err != nil { 18 return nil, err 19 } 20 21 // TODO: use printer.Format? Is the trailing newline an issue? 22 23 ast, err := hcl.Parse(string(b)) 24 if err != nil { 25 return nil, err 26 } 27 28 var buf bytes.Buffer 29 30 err = printer.Fprint(&buf, ast.Node) 31 if err != nil { 32 return nil, err 33 } 34 35 return buf.Bytes(), nil 36 } 37 38 func (Codec) Decode(b []byte, v map[string]interface{}) error { 39 return hcl.Unmarshal(b, &v) 40 }