Golang 打开浏览器 跨端方案
Open browser on multi platform by Golang
用Golang 代码打开浏览器并访问网址,你用对了么?
放“码”过来
自动判断平台,生成跨端启动浏览器命令
// browsers returns a list of commands to attempt for web visualization.
func browsers() []string {
var cmds []string
if userBrowser := os.Getenv("BROWSER"); userBrowser != "" {
cmds = append(cmds, userBrowser)
}
switch runtime.GOOS {
case "darwin":
cmds = append(cmds, "/usr/bin/open")
case "windows":
cmds = append(cmds, "cmd /c start")
default:
// Commands opening browsers are prioritized over xdg-open, so browser()
// command can be used on linux to open the .svg file generated by the -web
// command (the .svg file includes embedded javascript so is best viewed in
// a browser).
cmds = append(cmds, []string{"chrome", "google-chrome", "chromium", "firefox", "sensible-browser"}...)
if os.Getenv("DISPLAY") != "" {
// xdg-open is only for use in a desktop environment.
cmds = append(cmds, "xdg-open")
}
}
return cmds
}
启动浏览器并访问传入的网址
// open browser with url
func OpenBrowser(targetUrl string) (err error) {
// Construct URL.
u, _ := url.Parse(targetUrl)
for _, b := range browsers() {
args := strings.Split(b, " ")
if len(args) == 0 {
continue
}
viewer := exec.Command(args[0], append(args[1:], u.String())...)
viewer.Stderr = os.Stderr
if err = viewer.Start(); err == nil {
return
}
}
// No visualizer succeeded, so just print URL.
fmt.Println(u.String())
return
}
代码示例:
package main
import (
"fmt"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
func main() {
openBrowser("http://blog.itjsz.com")
time.Sleep(time.Second * 10)
}
初衷
当时我为了做一个开源项目—— https://github.com/PaulXu-cn/go-mod-graph-chart, 里面有个功能就是打开浏览器并访问 golang
启的 http
网页。在 Mac
下工作良好,在 Windows
下死活不唤起浏览器。
当时我查了好多资料,大多数给到我的信息是:
windows
下用start
darwin
Mac
用open
linux
统一用xdg-open
在 windows
上 bash
环境是有点兼容性问题的。后来我用了 golang 的 pprof 工具,发现它也需要跨端唤起 浏览器,我就去研究了下它代码。
代码地址 —— google/pprof
好,希望这简短的文章能帮到你,解决 golang 跨端 唤起浏览器问题。
PS: 刚看了下,网上那么多正确方案,我抄错了,还带到了开源项目里,订在commit里面了,死死地那种。
参考
- https://github.com/google/pprof
- https://github.com/pkg/browser