11package main
22
33import (
4- "io"
4+ "context"
5+ "encoding/json"
56 "log"
67 "net/http"
7- "net/url"
8- "strings "
8+
9+ "golang.org/x/oauth2 "
910)
1011
11- const (
12- redirectURI = "http://localhost:9094/oauth2"
13- serverURI = "http://localhost:9096"
14- clientID = "222222"
12+ var (
13+ config = oauth2.Config {
14+ ClientID : "222222" ,
15+ ClientSecret : "22222222" ,
16+ Scopes : []string {"all" },
17+ RedirectURL : "http://localhost:9094/oauth2" ,
18+ Endpoint : oauth2.Endpoint {
19+ AuthURL : "http://localhost:9096/authorize" ,
20+ TokenURL : "http://localhost:9096/token" ,
21+ },
22+ }
1523)
1624
1725func main () {
1826 http .HandleFunc ("/" , func (w http.ResponseWriter , r * http.Request ) {
19- u , err := url .Parse (serverURI + "/authorize" )
20- if err != nil {
21- panic (err )
22- }
23- q := u .Query ()
24- q .Add ("response_type" , "code" )
25- q .Add ("client_id" , clientID )
26- q .Add ("scope" , "all" )
27- q .Add ("state" , "xyz" )
28- q .Add ("redirect_uri" , url .QueryEscape (redirectURI ))
29- u .RawQuery = q .Encode ()
30- http .Redirect (w , r , u .String (), http .StatusFound )
27+ u := config .AuthCodeURL ("xyz" )
28+ http .Redirect (w , r , u , http .StatusFound )
3129 })
3230
3331 http .HandleFunc ("/oauth2" , func (w http.ResponseWriter , r * http.Request ) {
@@ -42,24 +40,14 @@ func main() {
4240 http .Error (w , "Code not found" , http .StatusBadRequest )
4341 return
4442 }
45- uv := url.Values {}
46- uv .Add ("code" , code )
47- uv .Add ("redirect_uri" , redirectURI )
48- uv .Add ("grant_type" , "authorization_code" )
49- uv .Add ("client_id" , clientID )
50- req , err := http .NewRequest (http .MethodPost , serverURI + "/token" , strings .NewReader (uv .Encode ()))
51- if err != nil {
52- http .Error (w , err .Error (), http .StatusInternalServerError )
53- return
54- }
55- req .Header .Set ("Content-Type" , "application/x-www-form-urlencoded" )
56- req .SetBasicAuth (clientID , "22222222" )
57- resp , err := http .DefaultClient .Do (req )
43+ token , err := config .Exchange (context .Background (), code )
5844 if err != nil {
5945 http .Error (w , err .Error (), http .StatusInternalServerError )
6046 return
6147 }
62- io .Copy (w , resp .Body )
48+ e := json .NewEncoder (w )
49+ e .SetIndent ("" , " " )
50+ e .Encode (* token )
6351 })
6452
6553 log .Println ("Client is running at 9094 port." )
0 commit comments