Use random available port number

This commit is contained in:
Mislav Marohnić 2019-10-09 16:00:34 +02:00
parent db0084f623
commit 216ffb89e2

View file

@ -1,23 +1,28 @@
package main
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"time"
)
func main() {
port := 3999 // TODO: find available port number
state := "TODO" // replace with random unguessable value
clientID := os.Getenv("GH_OAUTH_CLIENT_ID")
clientSecret := os.Getenv("GH_OAUTH_CLIENT_SECRET")
code := ""
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
panic(err)
}
port := listener.Addr().(*net.TCPAddr).Port
q := url.Values{}
q.Set("client_id", clientID)
q.Set("redirect_uri", fmt.Sprintf("http://localhost:%d", port))
@ -25,24 +30,19 @@ func main() {
q.Set("state", state)
cmd := exec.Command("open", fmt.Sprintf("https://github.com/login/oauth/authorize?%s", q.Encode()))
err := cmd.Run()
err = cmd.Run()
if err != nil {
panic(err)
}
code := ""
srv := &http.Server{Addr: fmt.Sprintf("localhost:%d", port)}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rq := r.URL.Query()
code = rq.Get("code")
// TODO: rq.Get("state")
w.Header().Add("content-type", "text/html")
fmt.Fprintf(w, "<p>You have authenticated <strong>GitHub CLI</strong>. You may now close this page.</p>")
time.AfterFunc(10*time.Millisecond, func() {
srv.Shutdown(context.TODO())
})
})
srv.ListenAndServe()
defer listener.Close()
}))
resp, err := http.PostForm("https://github.com/login/oauth/access_token",
url.Values{