dynamic - Dynamically create compiled binary with go -


first sorry perhaps bad title - imagine lot of difficulty i'm experiencing relates not knowing correct terminology i'm trying achieve.

in go, wish have program when run can dynamically create secondary binary. illustrate basic hello world example - in pseudo code since don't know how achieve it.

generator.go -> read in statement statement.txt (i.e. "hello world") -> insert statement following program...  package main  import (     "fmt" )  func main(){     fmt.println([dynamic statement inserted here]) }  -> compile code subprogram 

whenever go run generator.go executed subprogram binary created. running output hello world. changing statement.txt else , executing go run generator.go again once more create subprogram when run execute new statement.

in summary

with go, how can create program can dynamically create compiled child program output.

thanks.

so have 2 sub-tasks want:

  1. perform text substitution acquire final source code.
  2. compile final source code executable binary.

1. text substitution

the first can done using text/template package. can either have source templates separate, individual files, or embedded in main go source (e.g. consts).

you can build / parse source code templates , template e.g. template.parsefiles() or using template.new().parse(). once have template, assemble (e.g. load file) values want include in source template , execute e.g. template.execute(). have final source now.

the text/template package gives powerful template engine capable lot more text substitution.

note: there go parser implemented , available in standard library @ disposal in subpackages of go, using text/template package simpler , looks it's enough , fine case.

2. compile

to compile final source executable binary, need of compiler. can use os/exec package invoke compiler produce binary. see exec.command() function acquire cmd, , cmd.run() , cmd.start() execute it.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -