request.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package auth
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "runtime"
  9. "strconv"
  10. "github.com/jmorganca/ollama/version"
  11. )
  12. type RegistryOptions struct {
  13. Insecure bool
  14. Username string
  15. Password string
  16. Token string
  17. }
  18. func MakeRequest(ctx context.Context, method string, requestURL *url.URL, headers http.Header, body io.Reader, regOpts *RegistryOptions) (*http.Response, error) {
  19. if requestURL.Scheme != "http" && regOpts != nil && regOpts.Insecure {
  20. requestURL.Scheme = "http"
  21. }
  22. req, err := http.NewRequestWithContext(ctx, method, requestURL.String(), body)
  23. if err != nil {
  24. return nil, err
  25. }
  26. if headers != nil {
  27. req.Header = headers
  28. }
  29. if regOpts != nil {
  30. if regOpts.Token != "" {
  31. req.Header.Set("Authorization", "Bearer "+regOpts.Token)
  32. } else if regOpts.Username != "" && regOpts.Password != "" {
  33. req.SetBasicAuth(regOpts.Username, regOpts.Password)
  34. }
  35. }
  36. req.Header.Set("User-Agent", fmt.Sprintf("ollama/%s (%s %s) Go/%s", version.Version, runtime.GOARCH, runtime.GOOS, runtime.Version()))
  37. if s := req.Header.Get("Content-Length"); s != "" {
  38. contentLength, err := strconv.ParseInt(s, 10, 64)
  39. if err != nil {
  40. return nil, err
  41. }
  42. req.ContentLength = contentLength
  43. }
  44. proxyURL, err := http.ProxyFromEnvironment(req)
  45. if err != nil {
  46. return nil, err
  47. }
  48. client := http.Client{
  49. Transport: &http.Transport{
  50. Proxy: http.ProxyURL(proxyURL),
  51. },
  52. }
  53. resp, err := client.Do(req)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return resp, nil
  58. }