慕侠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))