How to load go file at runtime
You would need to embed a Go interpreter in your binary. Something like Yaegi
We want to create utility application.
Following are the steps
- Take input from user json file
2 . Load json to the structure ( go structure )
3 . load html template
4 . bind html with structure
in this case user can create any type of json . developer don’t know structure of the json . so we need some code where json and structure will get loaded .
The usual solution is to unmarshal into a map[string] interface{}
and then make decisions based on the map’s contents. You could use reflect.StructOf
to build a struct type dynamically, but that’s not very idiomatic Go. Go is bent to static, compile-time type safety rather than dynamic.
Since templates can be populated from maps, save a step and skip the struct.
Adding to what Jeff Emanuel said, give this a try to get yourself started:
package main
import (
"encoding/json"
"html/template"
"log"
"os"
)
var htmlTemplate = `
<h1>Template example</h1>
<ul>
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
</ul>`
func main() {
var dat map[string]interface{}
byt := []byte(`
{
"Some key I didn't know beforehand":42,
"Some other key":"Some string value",
"Hello": "World"
}`)
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
t := template.Must(template.New("t").Parse(htmlTemplate))
err := t.Execute(os.Stdout, dat)
if err != nil {
log.Fatal(err)
}
}
Here’s a playground link that you can run yourself and check the output. Your next question will be “but what about recursion?”. For that, see also:
- This question on the forum and my answer there
- This StackOverflow question with recursive template examples
- The docs
That should put you well on your journey. If you run in to any specific problems, come back and ask more specific questions. Good luck.
Thanks @packs for clarifying. Please ignore my previous answer then. I was under the impression that a Go binary shall load and execute a Go source file at runtime.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.