|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "log" |
| 8 | + "math/rand" |
| 9 | + "net/http" |
| 10 | + "os/exec" |
| 11 | + "runtime" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/fatih/color" |
| 15 | +) |
| 16 | + |
| 17 | +type HackerStory struct { |
| 18 | + Title string `json: "title"` |
| 19 | + Url string `json: "url"` |
| 20 | +} |
| 21 | + |
| 22 | +func openbrowser(url string) { |
| 23 | + var err error |
| 24 | + |
| 25 | + switch runtime.GOOS { |
| 26 | + case "linux": |
| 27 | + err = exec.Command("xdg-open", url).Start() |
| 28 | + case "windows": |
| 29 | + err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() |
| 30 | + case "darwin": |
| 31 | + err = exec.Command("open", url).Start() |
| 32 | + default: |
| 33 | + err = fmt.Errorf("unsupported platform") |
| 34 | + } |
| 35 | + if err != nil { |
| 36 | + log.Fatal(err) |
| 37 | + } |
| 38 | + |
| 39 | +} |
| 40 | + |
| 41 | +func main() { |
| 42 | + rand.Seed(time.Now().UnixNano()) |
| 43 | + topStoriesUrl := "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" |
| 44 | + |
| 45 | + resp, err := http.Get(topStoriesUrl) |
| 46 | + |
| 47 | + if err != nil { |
| 48 | + panic(err) |
| 49 | + } |
| 50 | + |
| 51 | + defer resp.Body.Close() |
| 52 | + |
| 53 | + body, err := io.ReadAll(resp.Body) |
| 54 | + if err != nil { |
| 55 | + panic(err) |
| 56 | + } |
| 57 | + var topStories []int64 |
| 58 | + err = json.Unmarshal(body, &topStories) |
| 59 | + if err != nil { |
| 60 | + panic(err) |
| 61 | + } |
| 62 | + |
| 63 | + randomStoryId := topStories[rand.Intn(len(topStories))] |
| 64 | + |
| 65 | + randomStoryUrl := fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json?print=pretty", randomStoryId) |
| 66 | + |
| 67 | + resp, err = http.Get(randomStoryUrl) |
| 68 | + if err != nil { |
| 69 | + panic(err) |
| 70 | + } |
| 71 | + |
| 72 | + body, err = io.ReadAll(resp.Body) |
| 73 | + if err != nil { |
| 74 | + panic(err) |
| 75 | + } |
| 76 | + |
| 77 | + var hackerStory HackerStory |
| 78 | + err = json.Unmarshal(body, &hackerStory) |
| 79 | + if err != nil { |
| 80 | + panic(err) |
| 81 | + } |
| 82 | + |
| 83 | + color.Green(hackerStory.Title) |
| 84 | + color.White(hackerStory.Url) |
| 85 | + |
| 86 | + openbrowser(hackerStory.Url) |
| 87 | + |
| 88 | +} |
0 commit comments