I'm able to run a Go application as a website with Apache using the following code.
hello.go:
package main
import (
"os"
)
func main() {
os.Stdout.WriteString("Content-Type: text/html; charset=UTF-8
")
os.Stdout.WriteString("Hello!
")
}
.htaccess:
AddHandler cgi-script .exe
I compile the app using go build hello.go
and going to http://localhost/hello.exe
works as expected.
But now I have to recompile after every change I make in the sourcecode.
Is it somehow possible to tell Apache to run hello.go
(Apache should run go run hello.go
) when visiting http://localhost/hello.go
?
By the way, this is only to speed development, not for production!
An easy solution would be to use a tool which re-compiles your code on changes to the source files. For example GoWatch
.
Or try it yourself by using fsnotify
as Erik already stated. Example: Simple Compile Daemon.
You could also invoke go run
in your CGI script.
Go is a compiled language, you'd need to compile it first. There currently aren't any interpreters/VM's for Go.
You're best bet is to just have a process/cron job that checks for the .go file being newer than the binary, and rebuilding it when it notices the file changed.
https://github.com/howeyc/fsnotify is a package that allows you to watch files for changes.
You could use gorun which enables you to put a #!/usr/bin/gorun
line at the top of the file so it is run like a script. gorun will compile it on the fly then run it. I've used it quite a bit for making golang scripts and I expect it would work for CGIs too.
You'd have to mark the script as executable (chmod +x
) and tell apache that the .go
extension was executable.
Not sure I'd recommend this for production but it should work reasonably efficiently as gorun
has a cache.