猿问

如何启动Web服务器以在golang的浏览器中打开页面?

如何使用 golang 在浏览器中临时打开网页?

就像这里是如何在python中使用HTTPServer完成的。


一只斗牛犬
浏览 387回答 3
3回答

慕侠2389804

您的问题有点误导,因为它询问如何在 Web 浏览器中打开本地页面,但您实际上想知道如何启动 Web 服务器以便可以在浏览器中打开它。对于后者(启动 Web 服务器以提供静态文件),您可以使用该http.FileServer()功能。有关更详细的答案,请参阅:Include js file in Go template和With golang webserver where does the root of the website map into the filesystem>。为您的文件夹提供服务的示例/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) {    fmt.Fprint(w, "Hello from Go")}func main() {    http.HandleFunc("/", myHandler)    panic(http.ListenAndServe(":8080", nil))}至于第一个(在默认浏览器中打开页面),Go 标准库中没有内置支持。但这并不难,您只需执行特定于操作系统的外部命令。您可以使用这个跨平台解决方案(我也在我的github.com/icza/gox库中发布了它,请参阅osx.OpenDefault()):// open opens the specified URL in the default browser of the user.func open(url string) error {    var cmd string    var args []string    switch runtime.GOOS {    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;披露:我是作者)。请注意,exec.Command()如果需要,执行特定于操作系统的参数引用。因此,例如,如果 URL 包含&,它将在 Linux 上正确转义,但是,它可能无法在 Windows 上运行。在 Windows 上,您可能必须自己手动引用它,例如将&符号替换"^&"为strings.ReplaceAll(url, "&", "^&").使用它在您的默认浏览器中打开之前启动的网络服务器:open("http://localhost:8080/")最后要注意的一件事:http.ListenAndServe()阻塞并且永不返回(如果没有错误)。所以你必须在另一个 goroutine 中启动服务器或浏览器,例如:go open("http://localhost:8080/")panic(http.ListenAndServe(":8080", nil))

慕容森

根据 Paul 的回答,这里有一个适用于 Windows 的解决方案:package mainimport (&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "os/exec"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; http.HandleFunc("/", myHandler)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; <-time.After(100 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; err := exec.Command("explorer", "http://127.0.0.1:8080").Run()&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; log.Println("running at port localhost:8080")&nbsp; &nbsp; log.Fatal(http.ListenAndServe(":8080", nil))}

拉风的咖菲猫

这是一个相当普遍的问题。你可以使用xdg-open程序为你做这件事。只需从 Go 运行该过程。will fork 自己,xdg-open所以我们可以简单地使用Run并等待进程结束。package mainimport "os/exec"func main() {&nbsp; &nbsp; exec.Command("xdg-open", "http://example.com/").Run()}
随时随地看视频慕课网APP

相关分类

Go
我要回答