使用go动态创建编译的二进制文件

First sorry for perhaps a bad title - I imagine a lot of the difficulty I'm experiencing relates to not knowing the correct terminology for what I'm trying to achieve.

In Go, I wish to have a program which when run can dynamically create a secondary binary. To illustrate with a basic hello world example - in pseudo code since I don't know how to achieve it.

generator.go
-> Read in statement from statement.txt (i.e. "Hello World")
-> Insert this statement into the following program...

package main

import (
    "fmt"
)

func main(){
    fmt.Println([dynamic statement inserted here])
}

-> compile this code into subprogram

Whenever go run generator.go is executed a subprogram binary is created. Running this would output Hello World. Changing statement.txt to something else and executing go run generator.go again would once more create subprogram which when run would execute the new statement.

In summary

With Go, how can I create a program which can dynamically create a compiled child program as output.

Thanks.

So you have 2 sub-tasks which together do what you want:

  1. Perform a text substitution to acquire the final source code.
  2. Compile the final source code into executable binary.

1. Text substitution

The first can be easily done using the text/template package. You can either have the source templates as separate, individual files, or embedded in the main Go source (e.g. as consts).

You can build / parse the source code templates and get a Template with e.g. template.ParseFiles() or using template.New().Parse(). Once you have your template, assemble (e.g. load from file) the values you want to include in the source template and execute it e.g. with Template.Execute(). You have the final source now.

The text/template package gives you a powerful template engine which is capable to a lot more than just text substitution.

Note: There is also a Go parser implemented and available in the standard library at your disposal in the subpackages of go, but using the text/template package is much simpler and looks it's enough and perfectly fine for your case.

2. Compile

To compile the final source into an executable binary, you need the help of the compiler. You can use the os/exec package to invoke the compiler which will produce the binary. See the exec.Command() function to acquire a Cmd, and Cmd.Run() and Cmd.Start() to execute it.