-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
85 lines (74 loc) · 2.16 KB
/
api.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package gollama
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// apiGet sends a GET request to the specified path on the Ollama server,
// and unmarshals the response into the given interface.
//
// The URL is built by joining the server address with the path.
//
// The Ollama server must respond with a JSON object that can be
// unmarshaled into the given interface.
//
// The Verbose flag is respected, and the URL is printed if it is set.
//
// The HTTPTimeout is used as the timeout for the HTTP request.
//
// If the request fails, or the response cannot be unmarshaled, an error
// is returned.
func (c *Gollama) apiGet(path string, v interface{}) error {
url, _ := url.JoinPath(c.ServerAddr, path)
if c.Verbose {
fmt.Printf("Sending a request to GET %s\n", url)
}
HTTPClient := &http.Client{
Timeout: c.HTTPTimeout,
}
resp, err := HTTPClient.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(v)
}
// apiPost sends a POST request to the specified path on the Ollama server,
// and unmarshals the response into the given interface.
//
// The URL is built by joining the server address with the path.
//
// The Ollama server must respond with a JSON object that can be
// unmarshaled into the given interface.
//
// The Verbose flag is respected, and the URL is printed if it is set.
//
// If the request fails, or the response cannot be unmarshaled, an error
// is returned.
//
// The HTTPTimeout is used as the timeout for the HTTP request, except for
// requests to the /api/pull endpoint, which is given the PullTimeout.
func (c *Gollama) apiPost(path string, v interface{}, data interface{}) error {
url, _ := url.JoinPath(c.ServerAddr, path)
if c.Verbose {
fmt.Printf("Sending a request to POST %s\n", url)
}
reqBytes, err := json.Marshal(data)
if err != nil {
return err
}
HTTPClient := &http.Client{
Timeout: c.HTTPTimeout,
}
if path == "/api/pull" {
HTTPClient.Timeout = c.PullTimeout
}
resp, err := HTTPClient.Post(url, "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(v)
}