3 回答

TA贡献1719条经验 获得超6个赞
您的问题有点误导,因为它询问如何在 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))

TA贡献1853条经验 获得超18个赞
根据 Paul 的回答,这里有一个适用于 Windows 的解决方案:
package main
import (
"log"
"net/http"
"os/exec"
"time"
)
func main() {
http.HandleFunc("/", myHandler)
go func() {
<-time.After(100 * time.Millisecond)
err := exec.Command("explorer", "http://127.0.0.1:8080").Run()
if err != nil {
log.Println(err)
}
}()
log.Println("running at port localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

TA贡献1995条经验 获得超2个赞
这是一个相当普遍的问题。你可以使用xdg-open程序为你做这件事。只需从 Go 运行该过程。will fork 自己,xdg-open所以我们可以简单地使用Run并等待进程结束。
package main
import "os/exec"
func main() {
exec.Command("xdg-open", "http://example.com/").Run()
}
- 3 回答
- 0 关注
- 386 浏览
添加回答
举报