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("Done")) // rw.Write([]byte("Done")) })) 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 }