Created
January 4, 2017 22:51
-
-
Save adelq/706fd5e6c5d1f94d68b19ba6db09b682 to your computer and use it in GitHub Desktop.
Recent Karma
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 main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
) | |
const userJSON = "https://www.reddit.com/user/%s.json" | |
type RedditUser struct { | |
Data struct { | |
Children []struct { | |
Data struct { | |
Score int `json:"score"` | |
LinkTitle string `json:"link_title"` | |
Subreddit string `json:"subreddit"` | |
} `json:"data"` | |
} `json:"children"` | |
} `json:"data"` | |
} | |
func main() { | |
un1, un2 := os.Args[1], os.Args[2] | |
user1, user2 := fetchUser(un1), fetchUser(un2) | |
if user1.Data.Children[0].Data.Score > user2.Data.Children[0].Data.Score { | |
fmt.Printf("%s has more likes than %s\n", un1, un2) | |
} else if user1.Data.Children[0].Data.Score < user2.Data.Children[0].Data.Score { | |
fmt.Printf("%s has more likes than %s\n", un2, un1) | |
} else { | |
fmt.Printf("%s and %s are tied!\n", un1, un2) | |
} | |
} | |
// Returns the karma on the most recent post for the given username | |
func fetchUser(username string) *RedditUser { | |
// Form HTTP request | |
c := &http.Client{} | |
req, err := http.NewRequest("GET", fmt.Sprintf(userJSON, username), nil) | |
if err != nil { | |
log.Fatalf("failed to create http request: %v", err) | |
} | |
req.Header.Add("User-Agent", "go:recentkarma:v0.0.0 (by /u/expiredmcat)") | |
// Request JSON | |
resp, err := c.Do(req) | |
if err != nil { | |
log.Fatalf("unable to fetch user: %v", err) | |
} | |
defer resp.Body.Close() | |
if resp.StatusCode == 429 { | |
log.Println("too many requests, trying again") | |
return fetchUser(username) | |
} | |
// Decode JSON | |
var user RedditUser | |
err = json.NewDecoder(resp.Body).Decode(&user) | |
if err != nil { | |
log.Fatalf("unable to decode json: %v", err) | |
} | |
return &user | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment