Skip to content

Commit 216ffb8

Browse files
committed
Use random available port number
1 parent db0084f commit 216ffb8

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

auth/oauth.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,48 @@
11
package main
22

33
import (
4-
"context"
54
"fmt"
65
"io/ioutil"
6+
"net"
77
"net/http"
88
"net/url"
99
"os"
1010
"os/exec"
11-
"time"
1211
)
1312

1413
func main() {
15-
port := 3999 // TODO: find available port number
1614
state := "TODO" // replace with random unguessable value
1715

1816
clientID := os.Getenv("GH_OAUTH_CLIENT_ID")
1917
clientSecret := os.Getenv("GH_OAUTH_CLIENT_SECRET")
2018

19+
code := ""
20+
listener, err := net.Listen("tcp", "localhost:0")
21+
if err != nil {
22+
panic(err)
23+
}
24+
port := listener.Addr().(*net.TCPAddr).Port
25+
2126
q := url.Values{}
2227
q.Set("client_id", clientID)
2328
q.Set("redirect_uri", fmt.Sprintf("http://localhost:%d", port))
2429
q.Set("scope", "repo")
2530
q.Set("state", state)
2631

2732
cmd := exec.Command("open", fmt.Sprintf("https://github.com/login/oauth/authorize?%s", q.Encode()))
28-
err := cmd.Run()
33+
err = cmd.Run()
2934
if err != nil {
3035
panic(err)
3136
}
3237

33-
code := ""
34-
srv := &http.Server{Addr: fmt.Sprintf("localhost:%d", port)}
35-
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
38+
http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3639
rq := r.URL.Query()
3740
code = rq.Get("code")
3841
// TODO: rq.Get("state")
3942
w.Header().Add("content-type", "text/html")
4043
fmt.Fprintf(w, "<p>You have authenticated <strong>GitHub CLI</strong>. You may now close this page.</p>")
41-
time.AfterFunc(10*time.Millisecond, func() {
42-
srv.Shutdown(context.TODO())
43-
})
44-
})
45-
srv.ListenAndServe()
44+
defer listener.Close()
45+
}))
4646

4747
resp, err := http.PostForm("https://github.com/login/oauth/access_token",
4848
url.Values{

0 commit comments

Comments
 (0)