/
webclient.go
69 lines (55 loc) · 1.3 KB
/
webclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package cmd
import (
"fmt"
"log"
"net/http"
"os/exec"
"runtime"
"github.com/spf13/cobra"
)
var webclientCmd = &cobra.Command{
Use: "webclient",
Short: "Run a GUI in your web browser",
Long: `Run a GUI in your web browser.`,
Run: func(cmd *cobra.Command, args []string) {
webclientCmdMain(args)
},
}
func init() {
rootCmd.AddCommand(webclientCmd)
}
func hello(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "hello\n")
}
func headers(w http.ResponseWriter, req *http.Request) {
for name, headers := range req.Header {
for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h)
}
}
}
func openbrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
log.Fatal(err)
}
}
func webclientCmdMain(args []string) {
portNumber := "8090"
// start a web server
http.HandleFunc("/", hello)
http.HandleFunc("/headers", headers)
// launch the default browser pointing to the local port you just listed to
openbrowser("http://localhost:" + portNumber)
http.ListenAndServe(":"+portNumber, nil)
}