golang调用windows文件的默认打开方式
最近在写的一个程序,需要使用golang调用windows下的一个html页面。在windows下调用的方式有两种,一种是通过 cmd 程序调用,另一种是通过rundll32.exe程序进行调用。
方式1:
1package main
2import (
3 "fmt"
4 "log"
5 "os/exec"
6 "path/filepath"
7 "strings"
8)
9func main() {
10 /*cmd := exec.Command("cmd", "/k", "start", "11.html")
11 //cmd.Dir = "c:\\"
12 cmd.Dir = "c:\\"
13 cmd.Start()*/
14 dir, err := filepath.Abs(filepath.Dir("brow.go"))
15 if err != nil {
16 log.Fatal(err)
17 }
18 newdir := strings.Replace(dir, `\`, `\\`, -1)
19 fmt.Println(dir)
20 fmt.Println(newdir)
21 cmd := exec.Command("cmd", "/k", "start", "11.html")
22 //cmd := exec.Command("cmd", "/c", "start", "www.baidu.com")
23 cmd.Dir = newdir
24 cmd.Start()
25}
cmd /k会扔旧会保留当前的cmd窗口,cmd /c调用结束后会自动关闭cmd窗口。
方式2:
1package main
2import (
3 "fmt"
4 "log"
5 "os/exec"
6 "runtime"
7)
8func openbrowser(url string) {
9 var err error
10 switch runtime.GOOS {
11 case "linux":
12 err = exec.Command("xdg-open", url).Start()
13 case "windows":
14 err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
15 case "darwin":
16 err = exec.Command("open", url).Start()
17 default:
18 err = fmt.Errorf("unsupported platform")
19 }
20 if err != nil {
21 log.Fatal(err)
22 }
23}
24func main() {
25 openbrowser("www.baidu.com")
26 openbrowser("c:\\11.html")
27}
这上面只是以html 和URL为例,其实对于pdf或xlsx、ppt文件等也是适用的。这个在windows7 版本上测试是成功的,在windows 2012上测试不通过,不过没有找到原因。
参考页面:
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/golang-win-process/6105.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.