huaZhangGui.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package external
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. )
  10. type HuaZhangGuiClient interface {
  11. GetWeather(ctx context.Context, city string) (string, error)
  12. PostUnReadMessage(ctx context.Context, reqData UnreadMessageRequest) (string, error)
  13. }
  14. type huaZhangGuiClient struct {
  15. httpClient *http.Client
  16. baseURL string
  17. }
  18. func NewHuaZhangGuiClient(baseURL string) HuaZhangGuiClient {
  19. return &huaZhangGuiClient{
  20. httpClient: &http.Client{Timeout: 5 * time.Second},
  21. baseURL: baseURL,
  22. }
  23. }
  24. func (c *huaZhangGuiClient) GetWeather(ctx context.Context, city string) (string, error) {
  25. req, _ := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/weather?city="+city, nil)
  26. resp, err := c.httpClient.Do(req)
  27. if err != nil {
  28. return "", err
  29. }
  30. defer resp.Body.Close()
  31. body, _ := ioutil.ReadAll(resp.Body)
  32. return string(body), nil
  33. }
  34. func (c *huaZhangGuiClient) PostUnReadMessage(ctx context.Context, reqData UnreadMessageRequest) (string, error) {
  35. jsonData, _ := json.Marshal(reqData)
  36. req, _ := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/unread_message", bytes.NewBuffer(jsonData))
  37. req.Header.Set("Content-Type", "application/json")
  38. resp, err := c.httpClient.Do(req)
  39. if err != nil {
  40. return "", err
  41. }
  42. defer resp.Body.Close()
  43. body, _ := ioutil.ReadAll(resp.Body)
  44. return string(body), nil
  45. }