Decode parses, decodes, and evaluates expressions in the given HCL source code, in a single step. The main HCL API is built to allow applications that need to decompose the processing steps into a pipeline, with different tasks done by different parts of the program: parsing the source code into an
(filename string, src []byte, ctx *hcl.EvalContext, target interface{})
| 56 | // just wrapping functionality elsewhere, if it doesn't meet your needs then |
| 57 | // please consider copying it into your program and adapting it as needed. |
| 58 | func Decode(filename string, src []byte, ctx *hcl.EvalContext, target interface{}) error { |
| 59 | var file *hcl.File |
| 60 | var diags hcl.Diagnostics |
| 61 | |
| 62 | switch suffix := strings.ToLower(filepath.Ext(filename)); suffix { |
| 63 | case ".hcl": |
| 64 | file, diags = hclsyntax.ParseConfig(src, filename, hcl.Pos{Line: 1, Column: 1}) |
| 65 | case ".json": |
| 66 | file, diags = json.Parse(src, filename) |
| 67 | default: |
| 68 | diags = diags.Append(&hcl.Diagnostic{ |
| 69 | Severity: hcl.DiagError, |
| 70 | Summary: "Unsupported file format", |
| 71 | Detail: fmt.Sprintf("Cannot read from %s: unrecognized file format suffix %q.", filename, suffix), |
| 72 | }) |
| 73 | return diags |
| 74 | } |
| 75 | if diags.HasErrors() { |
| 76 | return diags |
| 77 | } |
| 78 | |
| 79 | diags = gohcl.DecodeBody(file.Body, ctx, target) |
| 80 | if diags.HasErrors() { |
| 81 | return diags |
| 82 | } |
| 83 | return nil |
| 84 | } |
| 85 | |
| 86 | // DecodeFile is a wrapper around Decode that first reads the given filename |
| 87 | // from disk. See the Decode documentation for more information. |