Go调用浏览访问url连接

golang_horse.jpg

1.背景

开发程序的时候,须要打开浏览器,省去用户本身手动打开的麻烦,在golang中有方式能够直接代开,linux

start, xdg-open 分别是windows和mac, linux打开系统默认程序的工具,
因此你要使用谷歌打开就必需要把谷歌浏览器设置为默认,
linux下不要使用root权限使用xdg-open,windows下失败能够尝试在管理员权限下的cmd执行你的程序,git

  • windows 执行命令 cmd /C start htttp://tech.mojotv.cn
  • linux/freebsd/openbsd/netbsd 执行命令 xdg-open http://tech.mojotv.cn
  • mac 执行命令 start http://tech.mojotv.cn

2.代码

程序我就偷懒不写了,调用子程序就好了.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()
}

3.windows无GUI调用浏览器

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()
}

4.参考

相关文章
相关标签/搜索