Created
January 11, 2017 05:15
-
-
Save kamichidu/1304920b815b164bcd2e6cc9112dbf56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test | |
import ( | |
"github.com/pkg/browser" | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
"strings" | |
"sync" | |
"testing" | |
) | |
const ( | |
baseUrl = "http://localhost:9999" | |
) | |
func authorize(t *testing.T) error { | |
u, _ := url.Parse(baseUrl) | |
u.Path = "/oauth2/authorize" | |
q := u.Query() | |
q.Add("client_id", "koreha") | |
q.Add("redirect_uri", "http://localhost:12345") | |
q.Add("response_type", "code") | |
u.RawQuery = q.Encode() | |
t.Logf("visiting %s", u.String()) | |
return browser.OpenURL(u.String()) | |
} | |
func getAuthorizationCode(t *testing.T) ([]byte, error) { | |
var resp []byte | |
var err error | |
wg := new(sync.WaitGroup) | |
wg.Add(1) | |
go func() { | |
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { | |
w.WriteHeader(200) | |
u, _ := url.Parse(req.RequestURI) | |
q := u.Query() | |
code := q.Get("code") | |
if code != "" { | |
resp = []byte(code) | |
wg.Done() | |
} | |
}) | |
err = http.ListenAndServe("127.0.0.1:12345", http.DefaultServeMux) | |
}() | |
t.Log("Waiting authorization code...") | |
wg.Wait() | |
return resp, err | |
} | |
func TestOAuth2(t *testing.T) { | |
err := authorize(t) | |
if err != nil { | |
t.Fatal(err) | |
} | |
bytes, err := getAuthorizationCode(t) | |
if err != nil { | |
t.Fatal(err) | |
} | |
t.Log(string(bytes)) | |
u, _ := url.Parse(baseUrl) | |
u.Path = "/oauth2/token" | |
q := u.Query() | |
q.Add("client_id", "koreha") | |
q.Add("client_secret", "himitsu") | |
q.Add("redirect_uri", "http://localhost:12345") | |
q.Add("grant_type", "authorization_code") | |
q.Add("code", string(bytes)) | |
resp, err := http.Post(u.String(), "application/x-encoded", strings.NewReader(q.Encode())) | |
if err != nil { | |
t.Fatal(err) | |
} | |
bytes, err = ioutil.ReadAll(resp.Body) | |
if err != nil { | |
t.Fatal(err) | |
} | |
t.Logf("%d %s", resp.StatusCode, resp.Status) | |
t.Log(string(bytes)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment