Skip to content

Instantly share code, notes, and snippets.

@darcyliu
Created April 8, 2020 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darcyliu/6e581a81ad5751fdefa3123a3bb72216 to your computer and use it in GitHub Desktop.
Save darcyliu/6e581a81ad5751fdefa3123a3bb72216 to your computer and use it in GitHub Desktop.
Go web starter
package main
import (
"net/http"
"fmt"
"log"
"flag"
"net"
"time"
"runtime"
"os/exec"
)
var (
httpListen = flag.String("http", "127.0.0.1:8080", "host:port to listen on")
openBrowser = flag.Bool("openbrowser", false, "open browser automatically")
)
func viewHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Helllo World!")
}
func main() {
host, port, err := net.SplitHostPort(*httpListen)
if err != nil {
log.Fatal(err)
}
httpAddr := host + ":" + port
http.HandleFunc("/", viewHandler)
go func() {
fmt.Println("Started")
url := "http://" + httpAddr
if waitServer(url) && *openBrowser && startBrowser(url) {
log.Printf("A browser window should open. If not, please visit %s", url)
} else {
log.Printf("Please open your web browser and visit %s", url)
}
}()
log.Fatal(http.ListenAndServe(httpAddr, nil))
}
// waitServer waits some time for the http Server to start
// serving url. The return value reports whether it starts.
func waitServer(url string) bool {
tries := 20
for tries > 0 {
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
return true
}
time.Sleep(100 * time.Millisecond)
tries--
}
return false
}
// startBrowser tries to open the URL in a browser, and returns
// whether it succeed.
func startBrowser(url string) bool {
// try to start the browser
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment