这里介绍如何用go代码实现打开一个网页
也可以配合实现自建站点的打开
package main
import (
"fmt"
"net/http"
"os/exec"
"runtime"
"strings"
"time"
)
func main() {
//go Server()
r := Open("http://163.com")
//r := Open("http://127.0.0.1:8080")
fmt.Println(r)
time.Sleep(1000 * time.Second)
}
var commands = map[string]map[string]string{
"windows": map[string]string{"cmd": "cmd", "arg": "/c start"},
"darwin": map[string]string{"cmd": "open"},
"linux": map[string]string{"cmd": "xdg-open"},
}
// Open calls the OS default program for uri
func Open(url string) error {
_, ok := commands[runtime.GOOS]
if !ok {
return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS)
}
args := strings.Split(commands[runtime.GOOS]["arg"], " ")
args = append(args, url)
res := exec.Command(commands[runtime.GOOS]["cmd"], args...)
return res.Start()
}
func Server() {
//http.Dir() 将字符串路径转换成文件系统
h := http.FileServer(http.Dir("static")) //把本地static目录下资源建立一个文件服务器
http.Handle("/static/", http.StripPrefix("/static/", h)) // 启动静态文件服务
//启动
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
writer.Write([]byte("hello"))
})
//s:=http.Server{
// Addr: "127.0.0.1:8080",
// Handler: nil,
// TLSConfig: nil,
// ReadTimeout: 0,
// ReadHeaderTimeout: 0,
// WriteTimeout: 0,
// IdleTimeout: 0,
// MaxHeaderBytes: 0,
// TLSNextProto: nil,
// ConnState: nil,
// ErrorLog: nil,
// BaseContext: nil,
// ConnContext: nil,
//}
p := 8080
http.ListenAndServe(fmt.Sprintf(":%d", p), nil)
}