Skip to content

Instantly share code, notes, and snippets.

@wei0831
Last active August 21, 2018 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wei0831/f740c28b96404495e776ea8c1836d1e7 to your computer and use it in GitHub Desktop.
Save wei0831/f740c28b96404495e776ea8c1836d1e7 to your computer and use it in GitHub Desktop.
Twitch OAuth Token Flow
func main() {
// local server to capture token
go startSever()
openBrowser(fmt.Sprintf("https://id.twitch.tv/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=token&scope=%s", clientID, redirectURI, scope))
// TODO
for{
}
}
func startSever() {
r := mux.NewRouter()
r.HandleFunc("/twitch/", tokenHandler)
r.HandleFunc("/twitch/toekn", getTokenHandler)
log.Fatal(http.ListenAndServe(":8080", r))
}
// Redirect to capture the hash params
func tokenHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`<script>
window.location.replace("http://127.0.0.1:8080/twitch/toekn" + document.location.hash.replace("#", "?"))
</script>`)))
}
// Get query params
func getTokenHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Query())
w.WriteHeader(http.StatusOK)
w.Write([]byte(`<script>
close()
</script>`))
}
func openBrowser(url string) bool {
url = strings.Replace(url, "&", "^&", -1)
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
}
func main() {
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://id.twitch.tv/oauth2/validate", nil)
req.Header.Add("Authorization", fmt.Sprintf("OAuth %s", s))
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
res, _ := ioutil.ReadAll(resp.Body)
// Print raw string of res
fmt.Println(string(res))
// Print json data of res
var data map[string]interface{}
err = json.Unmarshal([]byte(res), &data)
if err != nil {
panic(err)
}
fmt.Println(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment