From 980a8bf16f8936f4ad6238b1e29e590d0513f76c Mon Sep 17 00:00:00 2001 From: Robert Gerus Date: Mon, 13 Jun 2016 19:22:21 +0200 Subject: [PATCH] Store tips fetched from api and only fetch a new batch when we've ran out of tips. --- bot/frog.go | 56 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/bot/frog.go b/bot/frog.go index ea5afbd..a43cec1 100644 --- a/bot/frog.go +++ b/bot/frog.go @@ -7,8 +7,8 @@ package bot import ( "encoding/json" "fmt" - "math/rand" "strings" + "sync" "github.com/arachnist/gorepost/irc" ) @@ -20,30 +20,50 @@ type tip struct { type tips struct { Tips []tip `json:"tips"` + lock sync.RWMutex } -func frog(output func(irc.Message), msg irc.Message) { - var values tips +func (tips *tips) fetchTips() error { + tips.lock.Lock() + defer tips.lock.Unlock() + data, err := httpGet("http://frog.tips/api/1/tips/") + if err != nil { + return err + } + + err = json.Unmarshal(data, tips) + if err != nil { + return err + } + + return nil +} + +func (tips *tips) popTip() string { + if len(tips.Tips) == 0 { + if err := tips.fetchTips(); err != nil { + return fmt.Sprint(err) + } + } + + tips.lock.RLock() + defer tips.lock.RUnlock() + + rmsg := tips.Tips[len(tips.Tips)-1].Tip + tips.Tips = tips.Tips[:len(tips.Tips)-1] + + return rmsg +} + +var t tips + +func frog(output func(irc.Message), msg irc.Message) { if strings.Split(msg.Trailing, " ")[0] != ":frog" { return } - data, err := httpGet("http://frog.tips/api/1/tips/") - if err != nil { - output(reply(msg, fmt.Sprint("error:", err))) - return - } - - err = json.Unmarshal(data, &values) - if err != nil { - output(reply(msg, fmt.Sprint("error:", err))) - return - } - - tip := values.Tips[rand.Intn(len(values.Tips))] - - output(reply(msg, fmt.Sprintf("frog tip #%d: %s", tip.Number, tip.Tip))) + output(reply(msg, t.popTip())) } func init() {