Go call browse to visit URL link

Time:2020-9-1

Go call browse to visit URL link

1. Background

When developing a program, you need to open the browser to save the trouble of manually opening it by users. There are ways to directly open it in golang,

Start and XDG open are the tools for windows, MAC and Linux to open the system default program,
So if you want to use Google to open, you have to set the Google browser as the default,
Do not use XDG open with root permission under Linux. If it fails in windows, you can try to execute your program with CMD under administrator permission,

  • Windows execute commandcmd /C start htttp://tech.mojotv.cn
  • Linux / FreeBSD / OpenBSD / NetBSDxdg-open http://tech.mojotv.cn
  • Mac execution commandstart http://tech.mojotv.cn

2. Code

I’m lazy not to write the program, just call the subroutine. Go doesn’t seem to need CMD / C under windows. It seems that shell will be used automatically
Let’s show you the code below

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 calls browser without GUI

package main

import (
    "os/exec"
)
func main() {
    //No GUI calls
    cmd := exec.Command("cmd", "/c", "start", "https://tech.mojotv.cn")
    cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
    cmd.Start()
}

4. Reference

  • stackoverflow
  • pkg/browser
  • Original address: tech.mojotv.cn Go advanced: go call browse link

Recommended Today

Build HTTP service with C + + Mongoose

Mongoose source code address:https://github.com/cesanta/mo… Mongoose user manual:https://www.cesanta.com/devel… Mngoose set up HTTP service #include <string> #include “mongoose.h” using namespace std; static const char *s_http_port = “8000”; static void ev_handler(mg_connection *nc, int ev, void *ev_data) { struct http_message *hm = (struct http_message *) ev_data; if (ev == MG_EV_HTTP_REQUEST) { std::string uri; if (hm->uri.p && hm->uri.p[0] == ‘/’) […]