简体   繁体   中英

Go build with built-in dependencies

I'm very new to system programming.

I have a Go program which uses net/http and starts an http server.

When I build a Windows binary and tried on a target Windows machine, nothing worked except Printf s before it starts the server.

As soon as I installed Go on the target Windows machine, everything started working!

Here is my program:

package main

import (
    "fmt"
    "log"
    "os/exec"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there @%s!", r.URL.Path[1:])
}

func main() {

    path, err := exec.LookPath("go")
    if err != nil {
        log.Fatal("Go is not your fortune :|")
    }
    fmt.Printf("Go is available at %s\n", path)

    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

If go doesn't build all the dependencies with its program then how do I do it? If it does, why it is not working?

Does target systems have to have go installed prior to run any Go programs?

Please help! Thanks.

Your app doesn't work without Go because you call log.Fatal() if it doesn't find the go tool, and log.Fatal() terminates your app:

Fatal is equivalent to Print() followed by a call to os.Exit(1) .

Your executable binary will contain everything it needs if you build it from the source you posted either with go build or go install (see What does go build build? for details). Just don't call log.Fatal() and it should work.

And on a side note: you should check and print errors returned by http.ListenAndServe() , eg:

panic(http.ListenAndServe(":8080", nil))

Because if this fails, you won't know why it doesn't work (eg you already started the app and the port is taken / in use).

No, the target system does not have to have the Go compiler installed for the executable compiled with Go to run. You can compile your program with go install or go build on one Windows computer, copy it to another one where Go is not installed and run it there.

Make sure the program that you compile starts with the package main statement - otherwise only a library file will be compiled.

Make sure to check whether the user that runs your program has rights to listen on the port that the http server uses. The ports 0-1023 - "Well Known Ports" - "can only be used by system (or root) processes or by programs executed by privileged users" ( https://support.microsoft.com/en-us/kb/174904 ), so try to start your program as a privileged user (for example, Administrator) or use a non-privileged port >= 1024 (ex. http.ListenAndServe(":8080", nil) should start the server on a non-privilege port. Take a very simple example - for example from https://golang.org/doc/articles/wiki/ - and see if you can get it to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM