haruhi

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 20, 2023 License: MIT Imports: 12 Imported by: 1

README

haruhi

Welcome! This is Sandy's take on making a simple yet powerful enough HTTP library. Inspired by python's requests.

haruhi

Motivation

When it comes to making network requests, I find myself writing a lot of repetitive go code, you know the gist of getting a json response,

req, err := http.NewRequestWithContext(context, method, URLpath, body)
if err != nil { ... }

params := req.URL.Query()
params.Add(key, value)
// more great parameters you need
req.URL.RawQuery = params.Encode()

resp, err := client.Do(req)
if err != nil { ... }
defer resp.Body.Close()

// do a response status check if needed...

ans := &SomeStruct{}
if err != json.NewDecoder(resp.Body).Decode(ans); err != nil { ... }

// whatever other magic you need to do

This is still a condensed version! The example above skips a couple of steps for brevity, like setting timeouts, deadlines, proper reading, buffering, progress, etc.

You can end up making something of your own, but repeating the same code has many issues, such as forgetting to close the response body or set proper contexts with plenty more.

Examples

What if instead, all you had to write was

ans := &SomeStruct{}
err := haruhi.URL(URLpath).
    Method(method).
    Params(params).
    Body(body).
    Timeout(time.Minute).
    ResponseJSON(ans)

and it did everything for you? You can even simplify it with haruhi's sensible defaults, such as running a GET request by default, etc, so you could even do

respStr, err := haruhi.URL(url).Get()

Haruhi of course, supports more funtionality that is aimed to be simple and straight-forward. Entire codebase is documented, so head on to go docs to see what else she can do.

Bad inputs, like setting handlers to nil will be ignored. Fatal errors when creating a request through Go or serializing bodies will be called with log.Fatalf.

Have fun requesting!

Similar projects

There is a golang requests project by Carl M. Johnson, who wrote a nice blog post about needing a nice http library to avoid many of mistakes mentioned above. It has been around for much longer (around 2 years?) and I've tried to use it. However, it may have been me misreading methods, or something else, but my requests weren't passing as I expected them to. And it's a powerful library, which can do roundtrip logging, redirect checkers, etc. However, most of the time, I want a dead-simple interface that "just works" and stays close to how I make fully proper go requests. Almost as if it's a bunch of macros.

I also found an older requests library, which I've never used but wanted to mention nonetheless.

Why Haruhi?

Because Endless Eight is a cinematic masterpiece and Haruhi is life itself.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Request

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

Request is an internal "staging" struct used when we want to track of what kind of Request user wants to make.

func URL

func URL(what string) *Request

URL will start building a request with the given URL (scheme+domain), an example is `https://go.dev` (notice without the path or parameters).

func (*Request) BasicAuth

func (r *Request) BasicAuth(username, password string) *Request

BasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.

func (*Request) Body

func (r *Request) Body(body io.Reader) *Request

Body tells us we need to read the body request from the reader.

func (*Request) BodyBytes

func (r *Request) BodyBytes(body []byte) *Request

BodyBytes will use slice of bytes as body.

func (*Request) BodyFormData

func (r *Request) BodyFormData(body url.Values) *Request

BodyFormData will take values and send them as formdata.

func (*Request) BodyJson

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

BodyXML will encode given interfact/instance into JSON and use that as body.

func (*Request) BodyString

func (r *Request) BodyString(body string) *Request

BodyString will use string as body.

func (*Request) BodyXML

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

BodyXML will encode given interfact/instance into XML and use that as body.

func (*Request) Client

func (r *Request) Client(client *http.Client) *Request

HTTP client to use, defaults to `http.DefaultClient`.

func (*Request) Context

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

Context will overwrite the current context with given value.

func (*Request) Deadline

func (r *Request) Deadline(deadline *time.Time) *Request

Deadline for the request (absolute time), defaults to `nil` (no deadline).

func (*Request) Delete

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

Make a blocking DELETE request and return the response as string.

func (*Request) ErrorHandler

func (r *Request) ErrorHandler(errorHandler func(*http.Response, error) error) *Request

ErrorHandler will set the error handler to be called if the request fails.

func (*Request) Get

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

Make a blocking GET request and return the response as string.

func (*Request) Header added in v0.2.0

func (r *Request) Header(name, value string) *Request

Headers will record headers to use in the request, will override defaults.

func (*Request) Headers

func (r *Request) Headers(headers http.Header) *Request

Headers will record headers to use in the request, will override defaults.

func (*Request) IfNotExpectedStatusCode added in v0.2.0

func (r *Request) IfNotExpectedStatusCode(statusCode int, handler func(*http.Response) error) *Request

IfNotExpectedStatusCode will set the handler to be called if the request does not return the expected status code.

func (*Request) Method

func (r *Request) Method(method string) *Request

Method to use in HTTP request, defaults to "GET" -- recommend using `http.Method...` constants.

func (*Request) Param added in v0.2.0

func (r *Request) Param(name, value string) *Request

Parameters to use in the URL.

func (*Request) Params

func (r *Request) Params(params url.Values) *Request

Parameters to use in the URL.

func (*Request) Path

func (r *Request) Path(path string) *Request

Path to navigate to, leading slash will be added if missing.

func (*Request) Post

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

Make a blocking POST request and return the response as string.

func (*Request) Put

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

Make a blocking PUT request and return the response as string.

func (*Request) Request

func (r *Request) Request() (*http.Request, context.CancelFunc, error)

Request will build the final haruhi request.

func (*Request) Response

func (r *Request) Response() (resp *http.Response, cancel context.CancelFunc, err error)

Make a non-blocking request and get the response object with cancel.

func (*Request) ResponseBody

func (r *Request) ResponseBody() (body io.ReadCloser, cancel context.CancelFunc, err error)

Make a request (parked) and get the body reader (needs closing) with cancel.

func (*Request) ResponseBuffer

func (r *Request) ResponseBuffer() (*bytes.Buffer, error)

Make a request and get the response as `*bytes.Buffer`.

func (*Request) ResponseBytes

func (r *Request) ResponseBytes() ([]byte, error)

Make a request and get the response as bytes.

func (*Request) ResponseJson

func (r *Request) ResponseJson(v any) error

Make a request and decode the JSON response into given interface.

func (*Request) ResponseString

func (r *Request) ResponseString() (string, error)

Make a request and get the response as a string.

func (*Request) ResponseXML

func (r *Request) ResponseXML(v any) error

Make a request and decode the XML response into given interface.

func (*Request) StatusCodeHandler added in v0.2.0

func (r *Request) StatusCodeHandler(statusCode int, handler func(*http.Response) error) *Request

StatusCodeHandler will set the handler to be called if the request returns given status code.

func (*Request) Timeout

func (r *Request) Timeout(timeout time.Duration) *Request

Timeout for the request, defaults to 0 (meaning no timeout).

Jump to

Keyboard shortcuts

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