~hokiegeek/fitstrava

ref: f5bac16231013630f1c8e6996ecfbe398a034d23 fitstrava/utils.go -rw-r--r-- 1.1 KiB
f5bac162HokieGeek Done and done 6 months ago
                                                                                
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
package fitstrava

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"net/http/httptest"

	"github.com/pkg/browser"
)

func codeFromWeb(port int, authURL string) string {
	l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
	if err != nil {
		log.Fatal(err)
	}

	ch := make(chan string)
	ts := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		query := req.URL.Query()
		code, present := query["code"]
		if !present {
			rw.WriteHeader(http.StatusBadRequest)
			rw.Write([]byte("Error"))
			panic("no code!")
		}

		ch <- code[0]

		rw.WriteHeader(http.StatusOK)
		rw.Write([]byte("<html><head><script>setInterval(function(){window.close();}, 1000);</script></head><body>Done</body></html>"))
		// rw.Write([]byte("<html><head><script>window.onload = function() { setInterval(function(){window.close();}, 1000); }</script></head><body>Done</body></html>"))

	}))

	ts.Listener.Close()
	ts.Listener = l
	ts.StartTLS()
	defer ts.Close()

	if err := browser.OpenURL(authURL); err != nil {
		fmt.Printf("Could not open browser. Click to authorize:\n%s", authURL)
	}
	code := <-ch

	return code
}