~handlerug/handlebot

ref: 7a899986d3a7d250418ed425c03a9e5391820979 handlebot/jisho/jisho.go -rw-r--r-- 1.3 KiB
7a899986Umar Getagazov Set user agent 3 months ago
                                                                                
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
package jisho

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
)

type Response struct {
	Meta Meta        `json:"meta"`
	Data []DataPoint `json:"data"`
}

type Meta struct {
	Status uint64 `json:"status"`
}

type DataPoint struct {
	Common   bool       `json:"is_common"`
	Tags     []string   `json:"tags"`
	Japanese []Japanese `json:"japanese"`
	Senses   []Senses   `json:"senses"`
}

type Japanese struct {
	Word    *string `json:"word"`
	Reading *string `json:"reading"`
}

type Senses struct {
	EnglishDefs   []string `json:"english_definitions"`
	PartsOfSpeech []string `json:"parts_of_speech"`
}

type Client struct {
	HTTPClient *http.Client
}

func (c *Client) Query(ctx context.Context, query string) (*Response, error) {
	req, _ := http.NewRequestWithContext(ctx, "GET", "https://jisho.org/api/v1/search/words", nil)
	q := url.Values{}
	q.Set("keyword", query)
	req.URL.RawQuery = q.Encode()

	resp, err := c.httpClient().Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var res Response
	if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
		return nil, fmt.Errorf("failed to parse JSON response: %w", err)
	}
	return &res, nil
}

func (c *Client) httpClient() *http.Client {
	if c.HTTPClient != nil {
		return c.HTTPClient
	}
	return http.DefaultClient
}