NewRequest creates an API request. A relative URL can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request
(ctx context.Context, method, urlStr string, body any, opts ...RequestOption)
| 778 | // specified, the value pointed to by body is JSON encoded and included as the |
| 779 | // request body. |
| 780 | func (c *Client) NewRequest(ctx context.Context, method, urlStr string, body any, opts ...RequestOption) (*http.Request, error) { |
| 781 | if !strings.HasSuffix(c.baseURL.Path, "/") { |
| 782 | return nil, fmt.Errorf("baseURL must have a trailing slash, but %q does not", c.baseURL) |
| 783 | } |
| 784 | |
| 785 | if err := checkURLPathTraversal(urlStr); err != nil { |
| 786 | return nil, err |
| 787 | } |
| 788 | |
| 789 | u, err := c.baseURL.Parse(urlStr) |
| 790 | if err != nil { |
| 791 | return nil, err |
| 792 | } |
| 793 | |
| 794 | var buf io.ReadWriter |
| 795 | if body != nil { |
| 796 | buf = &bytes.Buffer{} |
| 797 | enc := json.NewEncoder(buf) |
| 798 | enc.SetEscapeHTML(false) |
| 799 | err := enc.Encode(body) |
| 800 | if err != nil { |
| 801 | return nil, err |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | req, err := http.NewRequestWithContext(ctx, method, u.String(), buf) |
| 806 | if err != nil { |
| 807 | return nil, err |
| 808 | } |
| 809 | |
| 810 | if body != nil { |
| 811 | req.Header.Set("Content-Type", "application/json") |
| 812 | } |
| 813 | req.Header.Set("Accept", mediaTypeV3) |
| 814 | if c.userAgent != "" { |
| 815 | req.Header.Set("User-Agent", c.userAgent) |
| 816 | } |
| 817 | req.Header.Set(headerAPIVersion, defaultAPIVersion) |
| 818 | |
| 819 | for _, opt := range opts { |
| 820 | opt(req) |
| 821 | } |
| 822 | |
| 823 | return req, nil |
| 824 | } |
| 825 | |
| 826 | // NewFormRequest creates an API request. A relative URL can be provided in urlStr, |
| 827 | // in which case it is resolved relative to the BaseURL of the Client. |