启动网页服务器,http – 如何在golang中启动Web服务器在浏览器中打开页面?

您的问题有点误导,因为它询问如何在Web浏览器中打开本地页面,但您实际上想知道如何启动Web服务器以便可以在浏览器中打开它.

服务/ tmp / data文件夹的示例:

http.Handle("/", http.FileServer(http.Dir("/tmp/data")))

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

如果你想提供动态内容(由Go代码生成),你可以使用net/http包并编写自己的处理程序来生成响应,例如:

func myHandler(w http.ResponseWriter, r *http.Request) {undefined

fmt.Fprint(w, "Hello from Go")

}

func main() {undefined

http.HandleFunc("/", myHandler)

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

}

至于第一个(在默认浏览器中打开一个页面),Go标准库中没有内置支持.但这并不难,你只需要执行特定于操作系统的外部命令.您可以使用此跨平台解决方案:

// open opens the specified URL in the default browser of the user.

func open(url string) error {undefined

var cmd string

var args []string

switch runtime.GOOS {undefined

case "windows":

cmd = "cmd"

args = []string{"/c", "start"}

case "darwin":

cmd = "open"

default: // "linux", "freebsd", "openbsd", "netbsd"

cmd = "xdg-open"

}

args = append(args, url)

return exec.Command(cmd, args...).Start()

}

此示例代码取自Gowut(Go Web UI Toolkit;披露:我是作者).

使用此命令在默认浏览器中打开以前启动的Web服务器:

open("http://localhost:8080/")

最后要注意的是:http.ListenAndServe()块并且永不返回(如果没有错误).所以你必须在另一个goroutine中启动服务器或浏览器,例如:

go open("http://localhost:8080/")

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

posted @ 2022-04-09 11:29  China Soft  阅读(388)  评论(0编辑  收藏  举报