-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
79 lines (65 loc) · 1.76 KB
/
server.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package auth
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
type CallbackHandler struct {
Context context.Context
ContextCancel context.CancelFunc
CallbackFunc func(code string, state string) error
}
func (handler *CallbackHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
queryParts, _ := url.ParseQuery(r.URL.RawQuery)
if _, isExists := queryParts["code"]; !isExists {
fmt.Println("code does not exist.")
fmt.Fprintf(w, "invalid request")
return
}
code := queryParts["code"][0]
state := queryParts["state"][0]
// callback
handler.CallbackFunc(code, state)
defer handler.ContextCancel()
// show succes page
msg := "<p><strong>Success!</strong></p>"
msg = msg + "<p>You are authenticated and can now return to the CLI.</p>"
fmt.Fprintf(w, msg)
}
// Start callback local server
func StartCallbackServer(ctx context.Context, addr string, port string, path string, timeoutSec int16, callback func(code string, state string) error) {
ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSec)*time.Second)
handler := &CallbackHandler{
Context: ctx,
ContextCancel: cancel,
CallbackFunc: callback,
}
http.Handle(path, handler)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%s", addr, port),
}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
defer cancel()
select {
case <-ctx.Done():
// shutdown
//if err := srv.Shutdown(ctx); err != nil {
// log.Printf("%+v", err)
//}
if err := ctx.Err(); errors.Is(err, context.Canceled) {
// キャンセルされていた場合
fmt.Println("Success")
} else if errors.Is(err, context.DeadlineExceeded) {
// タイムアウトだった場合
fmt.Println("Time out")
}
}
}