4
4
"bufio"
5
5
"errors"
6
6
"fmt"
7
+ "io"
8
+ "net/http"
7
9
"os"
8
10
"regexp"
9
11
"strings"
@@ -90,13 +92,21 @@ var loginCmd = &cobra.Command{
90
92
viper .GetString ("base_url" ) +
91
93
"/cli/login" )
92
94
93
- reader := bufio .NewReader (os .Stdin )
94
- fmt .Print ("\n Paste your login code: " )
95
- text , err := reader .ReadString ('\n' )
95
+ inputChan := make (chan string )
96
96
97
- if err != nil {
98
- return err
99
- }
97
+ go func () {
98
+ reader := bufio .NewReader (os .Stdin )
99
+ fmt .Print ("\n Paste your login code: " )
100
+ text , _ := reader .ReadString ('\n' )
101
+ inputChan <- text
102
+ }()
103
+
104
+ go func () {
105
+ startHTTPServer (inputChan )
106
+ }()
107
+
108
+ // race the web server against the user's input
109
+ text := <- inputChan
100
110
101
111
re := regexp .MustCompile (`[^A-Za-z0-9_-]` )
102
112
text = re .ReplaceAllString (text , "" )
@@ -123,6 +133,35 @@ var loginCmd = &cobra.Command{
123
133
},
124
134
}
125
135
136
+ func cors (next http.Handler ) http.Handler {
137
+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
138
+ w .Header ().Set ("Access-Control-Allow-Methods" , "GET, POST, OPTIONS" )
139
+ w .Header ().Set ("Access-Control-Allow-Origin" , "*" )
140
+ next .ServeHTTP (w , r )
141
+ })
142
+ }
143
+ func startHTTPServer (inputChan chan string ) {
144
+ handleSubmit := func (res http.ResponseWriter , req * http.Request ) {
145
+ code , err := io .ReadAll (req .Body )
146
+ if err != nil {
147
+ return
148
+ }
149
+ inputChan <- string (code )
150
+ // Clear current line
151
+ fmt .Print ("\n \033 [1A\033 [K" )
152
+ }
153
+
154
+ handleHealth := func (res http.ResponseWriter , req * http.Request ) {
155
+ // 200 OK
156
+ }
157
+
158
+ http .Handle ("POST /submit" , cors (http .HandlerFunc (handleSubmit )))
159
+ http .Handle ("/health" , cors (http .HandlerFunc (handleHealth )))
160
+
161
+ // if we fail, oh well. we fall back to entering the code
162
+ _ = http .ListenAndServe ("localhost:9417" , nil )
163
+ }
164
+
126
165
func init () {
127
166
rootCmd .AddCommand (loginCmd )
128
167
}
0 commit comments