開發程序的時候,須要打開瀏覽器,省去用戶本身手動打開的麻煩,在golang中有方式能夠直接代開,linux
start, xdg-open 分別是windows和mac, linux打開系統默認程序的工具,
因此你要使用谷歌打開就必需要把谷歌瀏覽器設置爲默認,
linux下不要使用root權限使用xdg-open,windows下失敗能夠嘗試在管理員權限下的cmd執行你的程序,git
cmd /C start htttp://tech.mojotv.cn
xdg-open http://tech.mojotv.cn
start http://tech.mojotv.cn
程序我就偷懶不寫了,調用子程序就好了.go在windows下好像不須要 cmd /C,好像會自動使用shell
咱們下邊直接用代碼展現一下github
import ( "os/exec" ) // 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() }
package main import ( "os/exec" ) func main() { // 無GUI調用 cmd := exec.Command("cmd", "/c", "start", "https://tech.mojotv.cn") cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} cmd.Start() }