Skip to content

Instantly share code, notes, and snippets.

@adelq
Created January 4, 2017 22:04
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 adelq/30b2ebe9b6a3a1a35d1b72864c9fa2b7 to your computer and use it in GitHub Desktop.
Save adelq/30b2ebe9b6a3a1a35d1b72864c9fa2b7 to your computer and use it in GitHub Desktop.
Opening the Random Wikipedia Page
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os/exec"
"runtime"
)
const (
RandomURL = "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json"
PageFormat = "http://en.wikipedia.org/wiki?curid=%d"
)
type RandomPageQuery struct {
Query struct {
Random []struct {
ID int `json:"id"`
Title string `json:"title"`
} `json:"random"`
} `json:"query"`
}
func main() {
// Fetch JSON
resp, err := http.Get(RandomURL)
if err != nil {
log.Fatalf("unable to fetch random page: %v", err)
}
defer resp.Body.Close()
// Decode JSON
var rand RandomPageQuery
err = json.NewDecoder(resp.Body).Decode(&rand)
if err != nil {
log.Fatalf("unable to decode json: %v", err)
}
// Interactively ask user about reading article
fmt.Println("Welcome to Wikipedia's Random Pages!")
fmt.Println("------------------------------------")
for _, page := range rand.Query.Random {
fmt.Printf("Would you like to read about %s?\t", page.Title)
if askForConfirmation() {
open(fmt.Sprintf(PageFormat, page.ID))
break
}
}
}
// askForConfirmation uses Scanln to parse user input. A user must type in "yes" or "no" and
// then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as
// confirmations. If the input is not recognized, it will ask again. The function does not return
// until it gets a valid response from the user.
func askForConfirmation() bool {
var response string
_, err := fmt.Scanln(&response)
if err != nil {
log.Fatal(err)
}
okayResponses := []string{"y", "Y", "yes", "Yes", "YES"}
nokayResponses := []string{"n", "N", "no", "No", "NO"}
if containsString(okayResponses, response) {
return true
} else if containsString(nokayResponses, response) {
return false
} else {
fmt.Println("Please type yes or no and then press enter:")
return askForConfirmation()
}
}
func containsString(l []string, s string) bool {
for _, b := range l {
if b == s {
return true
}
}
return false
}
// open uses open or xdg-open depending on the platform to open a browser to the URL selected
func open(URL string) {
switch runtime.GOOS {
case "linux":
exec.Command("xdg-open", URL).Start()
case "windows", "darwin":
exec.Command("open", URL).Start()
default:
log.Fatal("unsupported platform")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment