Categorygithub.com/scottdware/go-rested
modulepackage
0.0.0-20160313143639-93e152ef32a6
Repository: https://github.com/scottdware/go-rested.git
Documentation: pkg.go.dev

# README

go-rested

GoDoc Travis-CI license

A Go package that makes calling RESTful API's easy.

Usage & Examples

Initiate the request, and set authentication (if applicable):

r := rested.NewRequest()
r.BasicAuth("user", "secret")

If you need to specify any headers or query parameters, then use a map[string]string type to define them:

headers := map[string]string{
	"Content-Type": "application/json",
	"Accept": "application/json",
}

query := map[string]string{
	"search_string": "dog",
	"results": "10",
}

Then, call the Send() function to issue the request. This function takes the following parameters:

ParameterDescription
methodThe HTTP method (i.e. GET, POST, DELETE, etc.)
uriThe URI/URL that you will be calling.
bodyThe contents of your request. This must be a byte slice ([]byte).
headersAny additional headers you want to send. Must be a map[string]string type.
queryAny additional query parameters you want to send. Must be a map[string]string type.
data := r.Send("get", "https://someurl/api/v1.0/stuff?default_param=something", nil, headers, query)

If you need to send/post a form, just place your form values in a map[string]string type and use the SendForm() function. The parameters are the same as the Send() function, except in place of the body parameter, you have your form values.

Note: headers and query parameters are the same as above.

formValues := map[string]string{
	"name": "Scott Ware",
	"age": "unknown",
	"sport": "Hockey",
}

data := r.SendForm("post", "https://someplace/to/upload", formValues, nil, nil)

If there was any type of error in your request, it will be defined in the Error field of the returned struct. You can check for errors similar to how you normally do in Go:

if data.Error != nil {
	fmt.Println(data.Error)
}

The returned data is a struct with the following fields:

type Response struct {
	Status  string
	Code    int
	Headers http.Header
	Body    []byte
	Error   error
}

You can see the payload by converting the Body field to a string:

fmt.Println(string(data.Body))

# Functions

NewRequest creates the state for our REST call.

# Structs

Request contains parameters to be defined before sending the request to the server.
Response contains the information returned from our request.