I'm writing a very simple script that just formats a build command via docker for go apps. It formats the command like this:
docker run --rm -v c:/Users/me/go/src/goapp:/go/src/goapp -w /go/src/goapp -e GOOS=os -e GOARCH=arch image go build -v -o outputname
When running this, however I get the following:
docker: Error response from daemon: the working directory ' /go/src/goapp' is invalid, it needs to be an absolute path
I tried reformatting it like this:
docker run --rm -v="c:/Users/me/go/src/goapp:/go/src/goapp" -w="/go/src/goapp" -e="GOOS=os" -e"GOARCH=arch" image go build -v -o outputname
and get the same error, only the "invalid" working directory is "/go/src/goapp"
Here's my code:
package main
import (
"bytes"
"flag"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
)
func constructCmd(volumeMap, workingDir, goos, goarch, output, image string) []string {
finalCmd := append([]string{"run", "--rm"},
fmt.Sprintf("-v='%s'", volumeMap),
fmt.Sprintf("-w='%s'", workingDir),
fmt.Sprintf("-e='%s'", goos),
fmt.Sprintf("-e='%s'", goarch),
)
finalCmd = append(finalCmd, image, "go build -v")
if output != "" {
finalCmd = append(finalCmd, fmt.Sprintf("-o %s", output))
}
return finalCmd
}
func main() {
// Parse flags
osPtr := flag.String("os", "windows", "Target distribution")
archPtr := flag.String("arch", "amd64", "Target distribution")
outputPtr := flag.String("out", "", "Output file name")
flag.Parse()
fmt.Printf("Building for %s/%s:
", *osPtr, *archPtr)
goos := "GOOS=" + *osPtr
goarch := "GOARCH=" + *archPtr
pwd, _ := os.Getwd()
if runtime.GOOS == "windows" {
pwd = strings.Replace(pwd, "C", "c", 1)
pwd = strings.Replace(pwd, "\\", "/", -1)
}
workingDir := pwd[strings.Index(pwd, "/go"):]
volumeMap := fmt.Sprintf("%s:%s", pwd, workingDir)
var image string
if len(flag.Args()) == 0 {
image = "golang"
} else {
image = flag.Args()[0]
}
execCmd := constructCmd(volumeMap, workingDir, goos, goarch, *outputPtr, image)
cmd := exec.Command("docker", execCmd...)
cmdOutput := &bytes.Buffer{}
cmd.Stdout = cmdOutput
cmd.Stderr = cmdOutput
err := cmd.Run()
if err != nil {
os.Stderr.WriteString(err.Error())
}
fmt.Print(string(cmdOutput.Bytes()))
}
To note, if I run this command directly, it works no problem. No error. So this isn't a docker problem, it's a go problem. What could cause this error?