-
Notifications
You must be signed in to change notification settings - Fork 1
/
quotes.go
76 lines (66 loc) · 1.57 KB
/
quotes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"fmt"
"github.com/dghubble/sling"
"os"
)
var (
quoteApi = sling.New().Base("https://favqs.com/api/")
qotdPath = "qotd.json"
quotesPath = "quotes"
defaultApiKey = "1501a5726d3be7d5839dc9085ba47848"
favqsApiKey string
)
func init() {
var ok bool
favqsApiKey, ok = os.LookupEnv("FAVQS_API_KEY")
if !ok {
favqsApiKey = defaultApiKey
}
}
type Quote struct {
Id int `json:"id"`
Body string `json:"body"`
Author string `json:"author"`
Tags []string `json:"tags"`
}
type QOTDResponse struct {
Quote Quote `json:"quote"`
}
type QuotesResponse struct {
Quotes []Quote `json:"quotes"`
}
// Quotes params
type QuoteParams struct {
Filter string `url:"filter,omitempty"`
Type string `url:"type,omitempty"`
Page int `url:"page,omitempty"`
}
func GetRandomQuote() (Quote, error) {
qotdResponse := QOTDResponse{}
_, err := quoteApi.Get(qotdPath).ReceiveSuccess(&qotdResponse)
return qotdResponse.Quote, err
}
func GetQuotes(search, author, tag string, max int) ([]Quote, error) {
quotesResponse := QuotesResponse{}
quotesQuery := QuoteParams{
Filter: search,
}
if author != "" {
quotesQuery.Filter = author
quotesQuery.Type = "author"
}
if tag != "" {
quotesQuery.Filter = tag
quotesQuery.Type = "tag"
}
_, err := quoteApi.Get(quotesPath).Add("Authorization", fmt.Sprintf("Token token=%s", favqsApiKey)).QueryStruct("esQuery).ReceiveSuccess("esResponse)
if err != nil {
return nil, err
}
quotes := quotesResponse.Quotes
if max < len(quotes) {
quotes = quotes[:max]
}
return quotes, nil
}