Total Lines | 51 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package fun |
||
2 | |||
3 | import ( |
||
4 | "bytes" |
||
5 | "encoding/json" |
||
6 | "errors" |
||
7 | "fmt" |
||
8 | "io" |
||
9 | "net/http" |
||
10 | ) |
||
11 | |||
12 | type ImageResponse struct { |
||
|
|||
13 | Error string `json:"error"` |
||
14 | Success bool `json:"success"` |
||
15 | ImageURL string `json:"image"` |
||
16 | } |
||
17 | |||
18 | func GetImageURL(category string) (string, error) { |
||
19 | resp, err := http.Get(fmt.Sprintf("https://botimages.realpha.ru/?category=%v", category)) |
||
20 | if err != nil && resp.StatusCode == http.StatusOK { |
||
21 | fmt.Printf("Getting image url error: %v", err) |
||
22 | return "", errors.New("getting image url error") |
||
23 | } |
||
24 | |||
25 | var result ImageResponse |
||
26 | |||
27 | err = json.NewDecoder(resp.Body).Decode(&result) |
||
28 | if err != nil { |
||
29 | return "", err |
||
30 | } |
||
31 | |||
32 | if result.Success { |
||
33 | return fmt.Sprintf("https://botimages.realpha.ru/%v", result.ImageURL), nil |
||
34 | } |
||
35 | return "", errors.New("wrong data") |
||
36 | } |
||
37 | |||
38 | func GetImage(category string) (*bytes.Buffer, error) { |
||
39 | resp, err := http.Get(fmt.Sprintf("https://botimages.realpha.ru/?category=%v", category)) |
||
40 | if err != nil { |
||
41 | fmt.Printf("Getting image url error: %v", err) |
||
42 | return nil, errors.New("getting image url error") |
||
43 | } |
||
44 | |||
45 | buf := new(bytes.Buffer) |
||
46 | |||
47 | _, err = io.Copy(buf, resp.Body) //png.Encode(buf, resp.Body) |
||
48 | if err != nil { |
||
49 | fmt.Printf("Map image: %v", err.Error()) |
||
50 | } |
||
51 | return buf, err |
||
52 | } |
||
53 |