requests

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2021 License: MIT Imports: 10 Imported by: 0

README

requests

Go Reference GitHub go.mod Go version Go Test Go Report Card GitHub GitHub last commit Sourcegraph CodeFactor

created by Austin Poor

A quick and easy HTTP request library written in Go.

This library is inspired by the Python Requests library. I wrote it for myself in order to make the HTTP client process a little more ergonomic when writing Go code.

Check out some more examples and documentation here: a-poor.github.io/requests

Table of Contents

Installation

Installation is quick and easy!

go get github.com/a-poor/requests

Quick Start

Here's a quick example of requests in action.

package main

import (
    "fmt"
    "github.com/a-poor/requests"
)

func main() {
    // Send the request
    res, err := requests.SendGetRequest("https://google.com")

    // If there was an error, print and return
    if err != nil {
        fmt.Printf("Error: %e\n", err)
        return
    }

    // Print the response's status code
    fmt.Printf("Status Code: %d\n", res.StatusCode)

}

Dependencies

Only the standard library!

Contributing

Pull requests are super welcome! For major changes, please open an issue first to discuss what you would like to change. And please make sure to update tests as appropriate.

Or... feel free to just open an issue with some thoughts or suggestions or even just to say Hi and tell me if this library has been helpful!

License

MIT

To-Do / Roadmap

  • Update documentation (mkdocs)

  • Update documentation (in-code)

  • Update tests

  • Add benchmarks

  • Add examples

  • Move to v1?

  • Add a helper POST-JSON function (aka SendPostRequest with an application/json content type. And maybe also wraps json.Marshal?)

  • Add a helper HTTP Method enum from string fn?

Documentation

Index

Examples

Constants

View Source
const (
	MIMEDefaultText   = "text/plain"
	MIMEDefaultBinary = "application/octet-stream"
)

Default MIME types for unknown text or binary files.

If the MIME type can't be guessed from the MIMETypes map, use one of these defaults, depending on if the file is text or binary.

Variables

View Source
var MIMETypes = map[string]string{
	".aac":    "audio/aac",
	".abw":    "application/x-abiword",
	".arc":    "application/x-freearc",
	".avi":    "video/x-msvideo",
	".azw":    "application/vnd.amazon.ebook",
	".bin":    "application/octet-stream",
	".bmp":    "image/bmp",
	".bz":     "application/x-bzip",
	".bz2":    "application/x-bzip2",
	".cda":    "application/x-cdf",
	".csh":    "application/x-csh",
	".css":    "text/css",
	".csv":    "text/csv",
	".doc":    "application/msword",
	".docx":   "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
	".eot":    "application/vnd.ms-fontobject",
	".epub":   "application/epub+zip",
	".gz":     "application/gzip",
	".gif":    "image/gif",
	".htm":    "text/html",
	".html":   "text/html",
	".ico":    "image/vnd.microsoft.icon",
	".ics":    "text/calendar",
	".jar":    "application/java-archive",
	".jpeg":   "image/jpeg",
	".jpg":    "image/jpeg",
	".js":     "text/javascript",
	".json":   "application/json",
	".jsonld": "application/ld+json",
	".mid":    "audio/midi",
	".midi":   "audio/midi",
	".mjs":    "text/javascript",
	".mp3":    "audio/mpeg",
	".mp4":    "video/mp4",
	".mpeg":   "video/mpeg",
	".mpkg":   "application/vnd.apple.installer+xml",
	".odp":    "application/vnd.oasis.opendocument.presentation",
	".ods":    "application/vnd.oasis.opendocument.spreadsheet",
	".odt":    "application/vnd.oasis.opendocument.text",
	".oga":    "audio/ogg",
	".ogv":    "video/ogg",
	".ogx":    "application/ogg",
	".opus":   "audio/opus",
	".otf":    "font/otf",
	".png":    "image/png",
	".pdf":    "application/pdf",
	".php":    "application/x-httpd-php",
	".ppt":    "application/vnd.ms-powerpoint",
	".pptx":   "application/vnd.openxmlformats-officedocument.presentationml.presentation",
	".rar":    "application/vnd.rar",
	".rtf":    "application/rtf",
	".sh":     "application/x-sh",
	".svg":    "image/svg+xml",
	".swf":    "application/x-shockwave-flash",
	".tar":    "application/x-tar",
	".tif":    "image/tiff",
	".tiff":   "image/tiff",
	".ts":     "video/mp2t",
	".ttf":    "font/ttf",
	".txt":    "text/plain",
	".vsd":    "application/vnd.visio",
	".wav":    "audio/wav",
	".weba":   "audio/webm",
	".webm":   "video/webm",
	".webp":   "image/webp",
	".woff":   "font/woff",
	".woff2":  "font/woff2",
	".xhtml":  "application/xhtml+xml",
	".xls":    "application/vnd.ms-excel",
	".xlsx":   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
	".xml":    "application/xml",
	".xul":    "application/vnd.mozilla.xul+xml",
	".zip":    "application/zip",
	".3gp":    "video/3gpp",
	".3g2":    "video/3gpp2",
	".7z":     "application/x-7z-compressed",
}

MIMETypes maps file extensions to MIME types. The map keys are lower-cased and include the leading period.

The data comes from the MDN Web Docs page for common MIME types:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

The data isn't meant to be complete but to be a good starting point for helping the user guess an unknown MIME type.

There are somes caveats listed in the MDN page:

  • ".mid" is set to "audio/midi" but could also be "audio/x-midi"
  • ".3gp" is set to "video/3gpp" but could also be "audio/3gpp" if it doesn't contain video
  • ".3g2" is set to "video/3gpp2" but could also be "audio/3gpp2" if it doesn't contain video
  • ".xml" is set to "application/xml" but in some older implementations could also be "text/xml"

If you can't find a sutable MIME type for your file from this map, try using either of the supplied defaults, depending on if the file is binary or not:

const (
	MIMEDefaultText   = "text/plain"
	MIMEDefaultBinary = "application/octet-stream"
)

Functions

func GuessMIME added in v0.7.0

func GuessMIME(filename string) (string, bool)

GuessMIME is a helper function for guessing the MIME type of a file, based on it's filename using the MIMETypes map.

It returns the MIME type and a boolean indicating if it was in the map or not.

If a MIME type can't be determined from the filename, consider using either MIMEDefaultText or MIMEDefaultBinary, depending on if the file is binary or not.

func GuessMIMEWithDefault added in v0.8.0

func GuessMIMEWithDefault(filename string, defaultMIME string) string

GuessMIMEWithDefault is a helper function for guessing the MIME type using GuessMIME but returning `defaultMIME` if the MIME type can't be guessed.

Consider using `MIMEDefaultText` or `MIMEDefaultBinary` as `defaultMIME`.

func JSONMust added in v0.3.0

func JSONMust(data map[string]interface{}) []byte

JSONMust marshals a map into a JSON byte slice using json.Marshal and panics if there is an error.

func URLEncode added in v0.6.0

func URLEncode(data interface{}) string

URLEncode will encode `data` as a URL-safe string Uses fmt.Sprint and url.PathEscape to do the encoding.

Types

type HTTPMethod

type HTTPMethod int

HTTPMethod is a type that represents an HTTP request method. Read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

const (
	GET     HTTPMethod = iota // An HTTP GET method
	POST                      // An HTTP POST method
	PUT                       // An HTTP PUT method
	DELETE                    // An HTTP DELETE method
	OPTIONS                   // An HTTP OPTIONS method
	HEAD                      // An HTTP HEAD method
	CONNECT                   // An HTTP CONNECT method
	TRACE                     // An HTTP TRACE method
	PATCH                     // An HTTP PATCH method
)

Enums representing HTTP methods

func (HTTPMethod) String

func (m HTTPMethod) String() string

Convert an HTTPMethod to it's string format

type Request

type Request struct {
	URL     string            // URL to send the request to
	Method  HTTPMethod        // HTTP method to use
	Headers map[string]string // Headers to send with the request
	Query   map[string]string // Query parameters to send with the request
	Body    []byte            // Body to send with the request
	Timeout time.Duration     // Timeout for the request
}

Request is a type that represents an HTTP request

Notes:

  • Headers and Query dont support multiple values
  • Timeout of 0 means no timeout

func NewGetRequest added in v0.1.0

func NewGetRequest(url string) *Request

NewGetRequest creates a new Request object with the supplied URL and sets the HTTP method to GET.

func NewPostRequest added in v0.1.0

func NewPostRequest(url string, contentType string, body []byte) *Request

NewPostRequest creates a new Request object with the supplied URL, content-type header, and body sets the HTTP method to POST.

func (*Request) Copy added in v0.6.0

func (req *Request) Copy() *Request

Copy will create a copy of the Request object

func (*Request) DelHeader

func (req *Request) DelHeader(name string)

DelHeader deletes a header value from the request headers if it exists. Normalizes the key to lowercase before deleting.

func (*Request) DelQuery added in v0.5.0

func (req *Request) DelQuery(name string)

DelQuery deletes a query value from the request headers if it exists.

func (*Request) GetHeader

func (req *Request) GetHeader(name string) (string, bool)

GetHeader gets a header value from the request. Normalizes the key to lowercase before checking. Returns the value associated with the key and whether it exists.

func (*Request) GetQuery added in v0.5.0

func (req *Request) GetQuery(name string) (string, bool)

GetQuery gets a query value from the request. Returns the value associated with the key and whether it exists.

func (*Request) MustParsePathParams added in v0.6.0

func (req *Request) MustParsePathParams(data interface{}) *Request

MustParsePathParams is the same as ParsePathParams except it panics if there is an error.

func (*Request) MustSend

func (req *Request) MustSend() *Response

MustSend sends the HTTP request and panic if an error is returned. (Calls Send() internally)

func (*Request) ParsePathParams added in v0.6.0

func (req *Request) ParsePathParams(data interface{}) (*Request, error)

ParsePathParams will create a copy of the Request object and replace URL parameters with the supplied data.

Note: The URL template has access to the `URLEncode` function which can be used to safely encode a string. (ex `{{ "Hello world" | URLEncode }}` will return `Hello%20world`)

func (*Request) Send

func (req *Request) Send() (*Response, error)

Send sends the HTTP request with the supplied parameters

Example
package main

import (
	"fmt"

	"github.com/a-poor/requests"
)

func main() {
	r := requests.Request{
		Method: requests.GET,
		URL:    "http://example.com",
	}
	res, err := r.Send()
	if err != nil {
		// handle error
	}
	fmt.Println(res.StatusCode)
}
Output:

200

func (*Request) SetHeader

func (req *Request) SetHeader(name, value string)

SetHeader sets a header value in the request. Normalizes the key to lowercase before setting.

func (*Request) SetQuery added in v0.5.0

func (req *Request) SetQuery(name, value string)

SetQuery sets a header value in the request.

type Response

type Response struct {
	Ok         bool              // Was the request successful? (Status codes: 100-399)
	StatusCode int               // HTTP response status code
	Headers    map[string]string // HTTP Response headers
	Body       []byte            // HTTP Response body
}

Response is a type that represents an HTTP response returned from an HTTP request

func SendGetRequest added in v0.1.0

func SendGetRequest(url string) (*Response, error)

SendGetRequest creates a new HTTP GET request and sends it to the specified URL. Internally, calls `NewGetRequest(url).Send()`

Example
package main

import (
	"fmt"

	"github.com/a-poor/requests"
)

func main() {
	res, err := requests.SendGetRequest("http://example.com")
	if err != nil {
		// handle error
	}
	fmt.Println(res.StatusCode)
}
Output:

200

func SendPostRequest added in v0.1.0

func SendPostRequest(url string, contentType string, body []byte) (*Response, error)

SendPostRequest creates a new HTTP POST request and sends it to the specified URL. Internally, calls `NewPostRequest(url, contentType, body).Send()`

func (*Response) GetHeader

func (res *Response) GetHeader(name string) (string, bool)

GetHeader gets a header value from the response if it exists. Normalizes the key to lowercase before checking. Returns the value of the header and whether it exists.

func (*Response) JSON

func (res *Response) JSON() (map[string]interface{}, error)

JSON unmarshalls the response body into a map

Jump to

Keyboard shortcuts

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