rip

package module
v0.7.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2025 License: MIT Imports: 12 Imported by: 2

README


Logo

rip

I just want to REST in peace.

Installation

go get -u github.com/iwpnd/rip

Usage

package main

import (
  "context"
  "encoding/json"

  "github.com/iwpnd/rip"
  )

type BlogPost struct {
    Id string
    Content string
  }

type BlogApiClient struct {
    *rip.Client
}

func NewBlogApiClient(
    host string,
    options ...rip.Option
) (*BlogApiClient, error) {
    c, err := rip.NewClient(host, options...)
    if err != nil {
        return &BlogApiClient{}, err
    }
    return &BlogApiClient{c}, nil
}

func (c *BlogApiClient) GetById(
    ctx context.Context,
    id string
) (*BlogPost, error) {
    req, err := c.NR().
        SetHeader("Accept", "application/json").
        SetParams(rip.Params{"id": id})

    res, err := req.Execute(ctx, "GET", "/blog/:id")
    if err != nil {
        return &BlogPost{}, err
    }
    defer res.Close()

    b := &BlogPost{}
    err = rip.Unmarshal(res.Header().Get("Content-Type"), res.Body(), r)
    if err != nil {
        return &BlogPost, err
    }

    return b
}

func (c *BlogApiClient) Create(
    ctx context.Context,
    post BlogPost
) (*BlogPost, error) {
    b, err := json.Marshal(post)
    if err != nil {
        return &BlogPost, err
    }

    req := c.NR().
        SetHeaders(rip.Header{
          "Content-Type": "application/json",
          "Accept":       "application/json",
          }).
        SetBody(b)


    res, err := req.Execute(ctx, "POST", "/blog")
    if err != nil {
        return &Response{}, err
    }
    defer res.Close()

    b := &BlogPost{}
    err = rip.Unmarshal(res.Header().Get("Content-Type"), res.Body(), r)
    if err != nil {
        return &BlogPost, err
    }

    return b
}

func main() {
    c, err := NewBlogApiClient(
      "https://myblog.io",
      rip.WithDefaultHeaders(rip.Header{"x-api-key": os.Getenv("API_KEY_BLOGAPI")}),
      rip.WithTimeout(30)
    )
    if err != nil {
        panic("AAAH!")
    }

    ctx := context.Background()

    b, err := c.GetById(ctx, id)
    if err != nil {
        t.Errorf("could not get blogpost for id %v :(", id)
    }

    fmt.Printf("blogpost: \n %v\n\n", b)
}

License

MIT

Maintainer

Benjamin Ramser - @iwpnd

Project Link: https://github.com/iwpnd/rip

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrClientMissing = errors.New("use .NR() to create a new request instead")

ErrClientMissing occurs when Request is instantiated without Client.NR()

Functions

func IsJSON

func IsJSON(ct string) bool

IsJSON helper to determine content type

func Unmarshal

func Unmarshal(ct string, b []byte, d interface{}) error

Unmarshal helper

Types

type Client

type Client struct {
	Header Header
	// contains filtered or unexported fields
}

Client wraps an http client.

func NewClient

func NewClient(host string, options ...Option) (*Client, error)

NewClient creates a new Client

func (*Client) NR

func (c *Client) NR() *Request

NR creates a new request

type ClientOptions

type ClientOptions struct {
	Header  Header
	Timeout time.Duration
}

ClientOptions to configure the http client.

type Header = map[string]string

Header params passed to the request

type Option added in v0.2.0

type Option func(*Client)

Option to use in option pattern.

func WithCookieJar added in v0.7.2

func WithCookieJar(jar *cookiejar.Jar) Option

WithCookieJar sets a cookie jar on rips httpClient.

func WithDefaultHeaders added in v0.2.0

func WithDefaultHeaders(headers Header) Option

WithDefaultHeaders sets client default headers (e.g. x-api-key)

func WithTimeout added in v0.2.0

func WithTimeout(timeout time.Duration) Option

WithTimeout sets timeout in seconds on rips httpClient.

func WithTransport added in v0.7.5

func WithTransport(transport *http.Transport) Option

WithTransport sets a custom Transport.

type Params

type Params = map[string]any

Params passed to the request

type Query

type Query = map[string]any

Query are any query parameter passed to the request.

type Request

type Request struct {
	Body          any
	Header        http.Header
	Params        Params
	Path          string
	ContentLength int64
	Query         url.Values
	Result        any // NOTE: can I pass struct here to unmarshal resp body to?
	URL           string
	// contains filtered or unexported fields
}

Request is the RIP request.

func (*Request) Execute

func (r *Request) Execute(ctx context.Context, method, path string) (*Response, error)

Execute executes a given request using a method on a given path

func (*Request) SetBody

func (r *Request) SetBody(body any) *Request

SetBody to set a request body

func (*Request) SetContentLength added in v0.7.4

func (r *Request) SetContentLength(length int64) *Request

SetContentLength for when you want to overwrite the default behaviour of *http.Request to calculate Content-Length. see: https://pkg.go.dev/net/http#NewRequestWithContext

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader to set a single header

func (*Request) SetHeaders

func (r *Request) SetHeaders(header Header) *Request

SetHeaders to set multiple header as map[string]string

func (*Request) SetParams

func (r *Request) SetParams(params Params) *Request

SetParams to replace in path

func (*Request) SetQuery

func (r *Request) SetQuery(query Query) *Request

SetQuery to set query parameters

type Response

type Response struct {
	Request *Request

	Close func() error
	// contains filtered or unexported fields
}

Response the rip response wrapping the original request and response.

func NewResponse added in v0.7.1

func NewResponse(request *Request, rawResponse *http.Response) *Response

func (*Response) Body

func (r *Response) Body() []byte

Body returns Body as byte array

func (*Response) ContentLength added in v0.3.1

func (r *Response) ContentLength() int64

ContentLength returns the content-length.

func (*Response) Header

func (r *Response) Header() http.Header

Header method returns the response headers.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if StatusCode > 399

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if 199 < StatusCode < 300

func (*Response) RawBody

func (r *Response) RawBody() io.ReadCloser

RawBody returns raw response body. be sure to close

func (*Response) Status

func (r *Response) Status() string

Status returns the response status.

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the response status code.

func (*Response) String

func (r *Response) String() string

String method returns the body of the server response as String.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL