restreq

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2023 License: MIT Imports: 9 Imported by: 0

README

RestReq

Go Reference Go Report Card

RestReq is a wrapper around standard Go net/http client. In a simple call you can use json encoding, add headers and parse result. This should be sufficient in most use cases.

Features

  • Simple syntax
  • Only stdlib (no external dependencies)
  • JSON parsing
  • Debug logging

Quick Start

import "github.com/scootpl/restreq"

resp, err := restreq.New("http://example.com").
	AddHeader("X-TOKEN", authToken).
	Post()

Examples and Documentation

See GoDoc for more details.

Documentation

Overview

RestReq is a wrapper around standard Go net/http client. In a simple call you can use json encoding, add headers and parse result. This should be sufficient in most use cases.

Examples

- Simplest use

resp, err := restreq.New("http://example.com").Post()

- You can add a header

resp, err := restreq.New("http://example.com").
	AddHeader("X-TOKEN", authToken).
	Post()

- Use map with JSON payload

p := map[string]any{
	"string": "string",
	"bool": true,
	"float": 2.34,
}

resp, err := restreq.New("http://example.com").
	SetContentTypeJSON().
	SetJSONPayload(p).
	Post()

- JSON payload with KV

resp, err := restreq.New("http://example.com").
	SetContentTypeJSON().
	SetUserAgent("Client 1.0").
	AddJSONKeyValue("string", "string").
	AddJSONKeyValue("bool", true).
	AddJSONKeyValue("float", 2.34).
	Post()

Parsing response

- In the default behavior, the body of the response is copied to Response.Body, and you don't have to call http.Response.Body.Close()

resp, err := restreq.New("http://example.com").Post()

if err == nil {
	fmt.Printf("%s\n", resp.Body)
}

- Default behavior is convenient but not optimal, due to redundant copying. If you need high performance, you can disable this behavior and direct access to the io.Reader. Don't forget to call Response.Body.Close()

resp, err := restreq.New("http://example.com").
	WithBodyReader().
	Post()

if err == nil {
	defer resp.Response.Body.Close()
	b := bytes.NewBuffer([]byte{})
	b.ReadFrom(resp.Response.Body)
	fmt.Println(b.String())
}

- Get header value

value := resp.Header("token")

- Decode JSON

s := struct {
	Message string `json:"message,omitempty"`
}{}

err := resp.DecodeJSON(&s)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DebugFlag

type DebugFlag int32
const (
	// Debug request body
	ReqBody DebugFlag = 1 << iota
	// Debug request headers
	ReqHeaders
	// Debug request cookies
	ReqCookies
	// Debug response body
	RespBody
	// Debug response header
	RespHeaders
	// Debug response cookies
	RespCookies
)

DebugFlags to control logger behavior.

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request contains all methods to operate on REST API

func New

func New(u string) *Request

func (*Request) AddCookie

func (r *Request) AddCookie(c *http.Cookie) requester

AddCookie adds cookie to request.

func (*Request) AddHeader

func (r *Request) AddHeader(k string, v string) requester

AddHeader adds header with value.

func (*Request) AddJSONKeyValue

func (r *Request) AddJSONKeyValue(key string, value any) requester

AddJSONKeyValue converts KV to json byte array. You can add many KV, they will be added to the map and converted to an byte array when the request is sent.

func (*Request) Context

func (r *Request) Context(ctx context.Context) requester

Context sets context to ctx

func (*Request) Debug

func (r *Request) Debug(logger *log.Logger, flags DebugFlag) requester

Debug sets logger and debug flags. You can combine flags, ReqBody+ReqHeader etc.

func (*Request) Delete

func (r *Request) Delete() (*Response, error)

Delete executes the delete method

func (*Request) Get

func (r *Request) Get() (*Response, error)

Get executes the get method

func (*Request) Patch

func (r *Request) Patch() (*Response, error)

Patch executes the patch method

func (*Request) Post

func (r *Request) Post() (*Response, error)

Post executes the post method

func (*Request) Put

func (r *Request) Put() (*Response, error)

Put executes the put method

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) requester

SetBasicAuth sets basic auth with username and password.

func (*Request) SetContentType

func (r *Request) SetContentType(s string) requester

SetContentType sets Content-Type.

func (*Request) SetContentTypeJSON

func (r *Request) SetContentTypeJSON() requester

SetContentTypeJSON sets Content-Type to application/json.

func (*Request) SetHTTPClient

func (r *Request) SetHTTPClient(c httpClient) requester

SetHTTPClient sets external http client.

func (*Request) SetJSONPayload

func (r *Request) SetJSONPayload(p any) requester

SetJSONPayload encodes map or struct to json byte array.

func (*Request) SetTimeoutSec

func (r *Request) SetTimeoutSec(t int) requester

SetTimeoutSec sets connection timeout.

func (*Request) SetUserAgent

func (r *Request) SetUserAgent(s string) requester

SetUserAgent sets User-Agent header.

func (*Request) WithBodyReader added in v0.1.0

func (r *Request) WithBodyReader() requester

WithBodyReader allows direct reading from http.Response.Body without copying to restreq.Response.Body

type Response

type Response struct {
	*http.Response
	Body []byte
}

Response inherits from http.Response, so you can use almost every field and method of http.Response.

http.Response.Body is an exception. You cannot use it, because content of http.Response.Body is copied to Response.Body. You don't have to call http.Response.Body.Close()

func (*Response) DecodeJSON

func (r *Response) DecodeJSON(s any) error

DecodeJSON decodes JSON

func (*Response) Header

func (r *Response) Header(s string) string

Header returns header

Jump to

Keyboard shortcuts

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