Go httpserver
作者:互联网
//go build -ldflags="-s -w " -trimpath
//go build -ldflags "-s -w -H windowsgui" -trimpath
package main
import (
"fmt"
"log"
"net"
"net/http"
"os/exec"
"runtime"
"strconv"
"github.com/gobuffalo/packr"
)
func openbrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
log.Fatal(err)
}
}
func createListener() (l net.Listener, close func()) {
l, err := net.Listen("tcp", ":0")
if err != nil {
panic(err)
}
return l, func() {
_ = l.Close()
}
}
func main() {
l, close := createListener()
defer close()
box := packr.NewBox("./static")
content, _ := box.FindString("template.html")
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(content))
}))
log.Println("listening at", l.Addr().(*net.TCPAddr).Port)
openbrowser("http://127.0.0.1:" + strconv.Itoa((l.Addr().(*net.TCPAddr).Port)))
http.Serve(l, nil)
}
标签:httpserver,http,err,exec,url,func,Go,net 来源: https://www.cnblogs.com/yzpopulation/p/16332849.html