Last active
August 31, 2015 01:32
-
-
Save 178inaba/90c00d9bd679f8650a19 to your computer and use it in GitHub Desktop.
github oauth2 use http client, made with go.
This file contains hidden or 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 main | |
| import ( | |
| "bytes" | |
| "encoding/json" | |
| "fmt" | |
| "io/ioutil" | |
| "log" | |
| "os/exec" | |
| "golang.org/x/oauth2" | |
| ) | |
| func main() { | |
| conf := &oauth2.Config{ | |
| ClientID: "YOUR_CLIENT_ID", | |
| ClientSecret: "YOUR_CLIENT_SECRET", | |
| Scopes: []string{"gist"}, | |
| Endpoint: oauth2.Endpoint{ | |
| AuthURL: "https://github.com/login/oauth/authorize", | |
| TokenURL: "https://github.com/login/oauth/access_token", | |
| }, | |
| } | |
| url := conf.AuthCodeURL("state") | |
| fmt.Printf("Visit the URL for the auth dialog: %v\n", url) | |
| exec.Command("open", url).Start() | |
| fmt.Print("code: ") | |
| var code string | |
| if _, err := fmt.Scan(&code); err != nil { | |
| log.Fatal(err) | |
| } | |
| tok, err := conf.Exchange(oauth2.NoContext, code) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| fmt.Println("--------------------") | |
| fmt.Println("AccessToken:", tok.AccessToken) | |
| fmt.Println("TokenType:", tok.TokenType) | |
| fmt.Println("RefreshToken:", tok.RefreshToken) | |
| fmt.Println("Expiry:", tok.Expiry) | |
| fmt.Println("error:", err) | |
| client := conf.Client(oauth2.NoContext, tok) | |
| resp, err := client.Get("https://api.github.com/gists") | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| defer resp.Body.Close() | |
| // header | |
| for k, v := range resp.Header { | |
| fmt.Println("header key: ", k) | |
| for _, value := range v { | |
| fmt.Println("\theader value: ", value) | |
| } | |
| } | |
| // body | |
| body, err := ioutil.ReadAll(resp.Body) | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| var out bytes.Buffer | |
| if err := json.Indent(&out, body, "", "\t"); err != nil { | |
| fmt.Println(err) | |
| } | |
| fmt.Println(out.String()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment