47 lines
802 B
Go
47 lines
802 B
Go
|
|
package quotes
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"fmt"
|
||
|
|
"github.com/go-resty/resty/v2"
|
||
|
|
)
|
||
|
|
|
||
|
|
type HTTPService struct {
|
||
|
|
client *resty.Client
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewHTTPService() *HTTPService {
|
||
|
|
return &HTTPService{
|
||
|
|
client: resty.New(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *HTTPService) GetRandomQuote(ctx context.Context) (*Quote, error) {
|
||
|
|
var response []struct {
|
||
|
|
Q string `json:"q"`
|
||
|
|
A string `json:"a"`
|
||
|
|
}
|
||
|
|
|
||
|
|
resp, err := s.client.R().
|
||
|
|
SetContext(ctx).
|
||
|
|
SetResult(&response).
|
||
|
|
Get("https://zenquotes.io/api/random")
|
||
|
|
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("failed to fetch quote: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
if resp.IsError() {
|
||
|
|
return nil, fmt.Errorf("API error: %s", resp.Status())
|
||
|
|
}
|
||
|
|
|
||
|
|
if len(response) == 0 {
|
||
|
|
return nil, fmt.Errorf("no quotes returned from API")
|
||
|
|
}
|
||
|
|
|
||
|
|
return &Quote{
|
||
|
|
Text: response[0].Q,
|
||
|
|
Author: response[0].A,
|
||
|
|
}, nil
|
||
|
|
}
|