client.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "github.com/jmorganca/ollama/signature"
  10. )
  11. type Client struct {
  12. Name string
  13. Version string
  14. URL string
  15. HTTP http.Client
  16. Headers http.Header
  17. PrivateKey []byte
  18. }
  19. func checkError(resp *http.Response, body []byte) error {
  20. if resp.StatusCode >= 200 && resp.StatusCode < 400 {
  21. return nil
  22. }
  23. apiError := Error{Code: int32(resp.StatusCode)}
  24. err := json.Unmarshal(body, &apiError)
  25. if err != nil {
  26. // Use the full body as the message if we fail to decode a response.
  27. apiError.Message = string(body)
  28. }
  29. return apiError
  30. }
  31. func (c *Client) do(ctx context.Context, method string, path string, stream bool, reqData any, respData any) error {
  32. var reqBody io.Reader
  33. var data []byte
  34. var err error
  35. if reqData != nil {
  36. data, err = json.Marshal(reqData)
  37. if err != nil {
  38. return err
  39. }
  40. reqBody = bytes.NewReader(data)
  41. }
  42. url := fmt.Sprintf("%s%s", c.URL, path)
  43. req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
  44. if err != nil {
  45. return err
  46. }
  47. if c.PrivateKey != nil {
  48. s := signature.SignatureData{
  49. Method: method,
  50. Path: url,
  51. Data: data,
  52. }
  53. authHeader, err := signature.SignAuthData(s, c.PrivateKey)
  54. if err != nil {
  55. return err
  56. }
  57. req.Header.Set("Authorization", authHeader)
  58. }
  59. req.Header.Set("Content-Type", "application/json")
  60. req.Header.Set("Accept", "application/json")
  61. for k, v := range c.Headers {
  62. req.Header[k] = v
  63. }
  64. respObj, err := c.HTTP.Do(req)
  65. if err != nil {
  66. return err
  67. }
  68. defer respObj.Body.Close()
  69. respBody, err := io.ReadAll(respObj.Body)
  70. if err != nil {
  71. return err
  72. }
  73. if err := checkError(respObj, respBody); err != nil {
  74. return err
  75. }
  76. if len(respBody) > 0 && respData != nil {
  77. if err := json.Unmarshal(respBody, respData); err != nil {
  78. return err
  79. }
  80. }
  81. return nil
  82. }