How to load go file at runtime

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

  1. 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 (

var htmlTemplate = `
<h1>Template example</h1>
{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

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 {
	t := template.Must(template.New("t").Parse(htmlTemplate))
	err := t.Execute(os.Stdout, dat)
	if err != nil {

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:

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. :slight_smile:

1 Like

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.