dryvPacks

@dryv/go-client-sdkv0.1.0

A standard-library Go HTTP client SDK with typed models, enums and operations.

Go Client SDKClientsUnitPublished 7 days ago2 downloads

dryv pack add @dryv/go-client-sdk
4.5 KBRaw ↗
jinja
// Code generated by Dryv. DO NOT EDIT.

package {{ pack.inputs.package_name }}

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"reflect"
	"strings"
)

// Client configures HTTP calls generated from Dryv operations.
type Client struct {
	BaseURL    string
	HTTPClient *http.Client
	Headers    http.Header
}

// NewClient creates a client using the standard net/http transport.
func NewClient(baseURL string) *Client {
	return &Client{
		BaseURL:    strings.TrimRight(baseURL, "/"),
		HTTPClient: http.DefaultClient,
		Headers:    make(http.Header),
	}
}

// APIError is returned for non-2xx HTTP responses.
type APIError struct {
	Status  int
	Message string
	Payload any
}

func (e *APIError) Error() string {
	if e.Message != "" {
		return fmt.Sprintf("api request failed with status %d: %s", e.Status, e.Message)
	}
	return fmt.Sprintf("api request failed with status %d", e.Status)
}

func (c *Client) httpClient() *http.Client {
	if c != nil && c.HTTPClient != nil {
		return c.HTTPClient
	}
	return http.DefaultClient
}

func (c *Client) newRequest(
	ctx context.Context,
	method string,
	path string,
	body []byte,
	contentType string,
	headers map[string]any,
	cookies map[string]any,
) (*http.Request, error) {
	if c == nil {
		return nil, fmt.Errorf("dryv client is nil")
	}

	var reader io.Reader
	if body != nil {
		reader = bytes.NewReader(body)
	}

	req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, reader)
	if err != nil {
		return nil, err
	}

	for key, values := range c.Headers {
		for _, value := range values {
			req.Header.Add(key, value)
		}
	}
	for key, value := range headers {
		req.Header.Set(key, stringValue(value))
	}
	for name, value := range cookies {
		req.AddCookie(&http.Cookie{Name: name, Value: stringValue(value)})
	}
	if contentType != "" {
		req.Header.Set("Content-Type", contentType)
	}

	return req, nil
}

func (c *Client) do(req *http.Request, output any) error {
	response, err := c.httpClient().Do(req)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	payload, err := io.ReadAll(response.Body)
	if err != nil {
		return err
	}

	if response.StatusCode < 200 || response.StatusCode >= 300 {
		var decoded any
		message := strings.TrimSpace(string(payload))
		if len(payload) > 0 && json.Unmarshal(payload, &decoded) == nil {
			if object, ok := decoded.(map[string]any); ok {
				if candidate, ok := object["message"].(string); ok {
					message = candidate
				}
			}
		}
		return &APIError{Status: response.StatusCode, Message: message, Payload: decoded}
	}

	if output == nil || len(payload) == 0 || response.StatusCode == http.StatusNoContent {
		return nil
	}
	return json.Unmarshal(payload, output)
}

func unsupportedBinding(kind string) error {
	return fmt.Errorf("dryv Go client does not yet support %s HTTP bindings", kind)
}

func jsonBody(value any) ([]byte, error) {
	return json.Marshal(value)
}

func formBody(values map[string]any) []byte {
	form := url.Values{}
	for key, value := range values {
		addURLValue(form, key, value)
	}
	return []byte(form.Encode())
}

func appendQuery(path string, values map[string]any) string {
	query := url.Values{}
	for key, value := range values {
		addURLValue(query, key, value)
	}
	if encoded := query.Encode(); encoded != "" {
		separator := "?"
		if strings.Contains(path, "?") {
			separator = "&"
		}
		return path + separator + encoded
	}
	return path
}

func appendQueryObject(path string, value any) (string, error) {
	payload, err := json.Marshal(value)
	if err != nil {
		return "", err
	}

	var object map[string]any
	if err := json.Unmarshal(payload, &object); err != nil {
		return "", err
	}
	return appendQuery(path, object), nil
}

func addURLValue(values url.Values, key string, value any) {
	if value == nil {
		return
	}

	rv := reflect.ValueOf(value)
	if rv.Kind() == reflect.Pointer {
		if rv.IsNil() {
			return
		}
		value = rv.Elem().Interface()
		rv = reflect.ValueOf(value)
	}

	if rv.IsValid() && (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array) {
		for i := 0; i < rv.Len(); i++ {
			values.Add(key, fmt.Sprint(rv.Index(i).Interface()))
		}
		return
	}

	values.Add(key, fmt.Sprint(value))
}

func stringValue(value any) string {
	if value == nil {
		return ""
	}
	rv := reflect.ValueOf(value)
	if rv.Kind() == reflect.Pointer {
		if rv.IsNil() {
			return ""
		}
		return fmt.Sprint(rv.Elem().Interface())
	}
	return fmt.Sprint(value)
}

func replacePath(path string, name string, value any) string {
	return strings.ReplaceAll(path, "{"+name+"}", url.PathEscape(stringValue(value)))
}