Documentation ¶
Overview ¶
Package roundtrip provides convenient functions for building HTTP client wrappers and providing functions for server responses.
import ( "github.com/gravitational/roundtrip" ) type MyClient struct { roundtrip.Client // you can embed roundtrip client } func NewClient(addr, version string) (*MyClient, error) { c, err := roundtrip.NewClient(addr, version) if err != nil { return nil, err } return &MyClient{*c}, nil }
Copyright 2015 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Index ¶
- Constants
- func ReplyJSON(w http.ResponseWriter, code int, obj interface{})
- type AccessDeniedError
- type AuthCreds
- type Client
- func (c *Client) Delete(ctx context.Context, endpoint string) (*Response, error)
- func (c *Client) DeleteWithParams(ctx context.Context, endpoint string, params url.Values) (*Response, error)
- func (c *Client) Endpoint(params ...string) string
- func (c *Client) Get(ctx context.Context, endpoint string, params url.Values) (*Response, error)
- func (c *Client) GetFile(ctx context.Context, endpoint string, params url.Values) (*FileResponse, error)
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) OpenFile(ctx context.Context, endpoint string, params url.Values) (ReadSeekCloser, error)
- func (c *Client) PatchForm(ctx context.Context, endpoint string, vals url.Values, files ...File) (*Response, error)
- func (c *Client) PatchJSON(ctx context.Context, endpoint string, data interface{}) (*Response, error)
- func (c *Client) PostForm(ctx context.Context, endpoint string, vals url.Values, files ...File) (*Response, error)
- func (c *Client) PostJSON(ctx context.Context, endpoint string, data interface{}) (*Response, error)
- func (c *Client) PutForm(ctx context.Context, endpoint string, vals url.Values, files ...File) (*Response, error)
- func (c *Client) PutJSON(ctx context.Context, endpoint string, data interface{}) (*Response, error)
- func (c *Client) RoundTrip(fn RoundTripFn) (*Response, error)
- func (c *Client) SetAuthHeader(h http.Header)
- type ClientParam
- type File
- type FileResponse
- type NewTracer
- type NopTracer
- type ParameterError
- type ReadSeekCloser
- type RequestInfo
- type RequestTracer
- type Response
- type RoundTripFn
- type WriterTracer
Constants ¶
const ( // AuthBasic auth is username / password basic auth AuthBasic = "Basic" // AuthBearer auth is bearer tokens auth AuthBearer = "Bearer" // AccessTokenQueryParam URI query parameter AccessTokenQueryParam = "access_token" )
Variables ¶
This section is empty.
Functions ¶
func ReplyJSON ¶
func ReplyJSON(w http.ResponseWriter, code int, obj interface{})
ReplyJSON encodes the passed objec as application/json and writes a reply with a given HTTP status code to `w`
ReplyJSON(w, 404, map[string]interface{}{"msg": "not found"})
Types ¶
type AccessDeniedError ¶
AccessDeniedError is returned whenever access is denied
func (*AccessDeniedError) Error ¶
func (a *AccessDeniedError) Error() string
Error returns user-friendly description of this error
func (*AccessDeniedError) IsAccessDeniedError ¶
func (a *AccessDeniedError) IsAccessDeniedError() bool
IsAccessDeniedError indicates that this error belongs to access denied class of errors
type AuthCreds ¶
type AuthCreds struct { // Type is auth HTTP auth type (either Bearer or Basic) Type string // Username is HTTP username Username string // Password holds password in case of Basic auth, http token otherwize Password string }
AuthCreds hold authentication credentials for the given HTTP request
func ParseAuthHeaders ¶
ParseAuthHeaders parses authentication headers from HTTP request it currently detects Bearer and Basic auth types
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a wrapper holding HTTP client. It hold target server address and a version prefix, and provides common features for building HTTP client wrappers.
func NewClient ¶
func NewClient(addr, v string, params ...ClientParam) (*Client, error)
NewClient returns a new instance of roundtrip.Client, or nil and error
c, err := NewClient("http://localhost:8080", "v1") if err != nil { // handle error }
func (*Client) Delete ¶
Delete executes DELETE request to the endpoint with no body
re, err := c.Delete(c.Endpoint("users", "id1"))
func (*Client) DeleteWithParams ¶
func (c *Client) DeleteWithParams(ctx context.Context, endpoint string, params url.Values) (*Response, error)
DeleteWithParams executes DELETE request to the endpoint with optional query arguments
re, err := c.DeleteWithParams(c.Endpoint("users", "id1"), url.Values{"force": []string{"true"}})
func (*Client) Endpoint ¶
Endpoint returns a URL constructed from parts and version appended, e.g.
c.Endpoint("user", "john") // returns "/v1/users/john"
func (*Client) Get ¶
Get executes GET request to the server endpoint with optional query arguments passed in params
re, err := c.Get(c.Endpoint("users"), url.Values{"name": []string{"John"}})
func (*Client) GetFile ¶
func (c *Client) GetFile(ctx context.Context, endpoint string, params url.Values) (*FileResponse, error)
GetFile executes get request and returns a file like object
f, err := c.GetFile("files", "report.txt") // returns "/v1/files/report.txt"
func (*Client) HTTPClient ¶
HTTPClient returns underlying http.Client
func (*Client) OpenFile ¶
func (c *Client) OpenFile(ctx context.Context, endpoint string, params url.Values) (ReadSeekCloser, error)
OpenFile opens file using HTTP protocol and uses `Range` headers to seek to various positions in the file, this means that server has to support the flags `Range` and `Content-Range`
func (*Client) PatchForm ¶ added in v1.0.2
func (c *Client) PatchForm(ctx context.Context, endpoint string, vals url.Values, files ...File) (*Response, error)
PatchForm patches urlencoded form with values and returns the result
c.PatchForm(c.Endpoint("users"), url.Values{"name": []string{"John"}})
func (*Client) PatchJSON ¶
func (c *Client) PatchJSON(ctx context.Context, endpoint string, data interface{}) (*Response, error)
PatchJSON posts JSON "application/json" encoded request body and "PATCH" method
c.PatchJSON(c.Endpoint("users"), map[string]string{"name": "alice@example.com"})
func (*Client) PostForm ¶
func (c *Client) PostForm(ctx context.Context, endpoint string, vals url.Values, files ...File) (*Response, error)
PostForm posts urlencoded form with values and returns the result
c.PostForm(c.Endpoint("users"), url.Values{"name": []string{"John"}})
func (*Client) PostJSON ¶
func (c *Client) PostJSON(ctx context.Context, endpoint string, data interface{}) (*Response, error)
PostJSON posts JSON "application/json" encoded request body
c.PostJSON(c.Endpoint("users"), map[string]string{"name": "alice@example.com"})
func (*Client) PutForm ¶ added in v1.0.2
func (c *Client) PutForm(ctx context.Context, endpoint string, vals url.Values, files ...File) (*Response, error)
PutForm puts urlencoded form with values and returns the result
c.PutForm(c.Endpoint("users"), url.Values{"name": []string{"John"}})
func (*Client) PutJSON ¶
PutJSON posts JSON "application/json" encoded request body and "PUT" method
c.PutJSON(c.Endpoint("users"), map[string]string{"name": "alice@example.com"})
func (*Client) RoundTrip ¶
func (c *Client) RoundTrip(fn RoundTripFn) (*Response, error)
RoundTrip collects response and error assuming fn has done HTTP roundtrip
func (*Client) SetAuthHeader ¶
SetAuthHeader sets client's authorization headers if client was configured to work with authorization
type ClientParam ¶
ClientParam specifies functional argument for client
func BasicAuth ¶
func BasicAuth(username, password string) ClientParam
BasicAuth sets username and password for HTTP client
func CookieJar ¶
func CookieJar(jar http.CookieJar) ClientParam
CookieJar sets HTTP cookie jar for this client
func HTTPClient ¶
func HTTPClient(h *http.Client) ClientParam
HTTPClient is a functional parameter that sets the internal HTTPClient of the roundtrip client wrapper
func SanitizerEnabled ¶
func SanitizerEnabled(sanitizerEnabled bool) ClientParam
SanitizerEnabled will enable the input sanitizer which passes the URL path through a strict whitelist.
type FileResponse ¶
type FileResponse struct {
// contains filtered or unexported fields
}
FileResponse indicates HTTP server file response
func (*FileResponse) Body ¶
func (r *FileResponse) Body() io.ReadCloser
Body returns reader with HTTP response body
func (*FileResponse) Close ¶
func (r *FileResponse) Close() error
Close closes internal response body
func (*FileResponse) Code ¶
func (r *FileResponse) Code() int
Code returns HTTP response status code
func (*FileResponse) FileName ¶
func (r *FileResponse) FileName() string
FileName returns HTTP file name
func (*FileResponse) Headers ¶
func (r *FileResponse) Headers() http.Header
Headers returns http.Header dictionary with response headers
type NewTracer ¶
type NewTracer func() RequestTracer
NewTracer is a constructor function to create new instances of RequestTracer.
type NopTracer ¶
type NopTracer struct { }
NopTracer is a request tracer that does nothing
type ParameterError ¶
type ParameterError struct { trace.Traces Name string `json:"name"` Message string `json:"message"` }
ParameterError indicates error in parameter
func (*ParameterError) Error ¶
func (a *ParameterError) Error() string
Error returns user-friendly description of this error
func (*ParameterError) IsParameterError ¶
func (a *ParameterError) IsParameterError() bool
IsParameterError indicates that this error belongs to class of errors related to bad parameters
type ReadSeekCloser ¶
type ReadSeekCloser interface { io.ReadSeeker io.Closer }
ReadSeekCloser implements all three of Seeker, Closer and Reader interfaces
type RequestInfo ¶
type RequestInfo struct { // Method is request method Method string `json:"method"` // URL is request URL URL string `json:"url"` }
RequestInfo contains request information
type RequestTracer ¶
type RequestTracer interface { // Start starts tracing the specified request and is usually called // before any request handling takes place. Start(r *http.Request) // Done is called to complete tracing of the request previously started with Start. // It is designed to match the result of calling RoundTrip API for convenience // and does not modify the response argument. Done(re *Response, err error) (*Response, error) }
RequestTracer defines an interface to trace HTTP requests for debugging or collecting metrics.
Here's an example tracing a request by wrapping a handler between tracer's Start/Done methods:
func Handler(args ...) (*Response, error) { req := NewRequestTracer() return req.Done(func(*Response, error) { // Handler implementation }) }
func NewNopTracer ¶
func NewNopTracer() RequestTracer
NewNopTracer is a function that returns no-op tracer every time when called
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response indicates HTTP server response
func ConvertResponse ¶
ConvertResponse converts http error to internal error type based on HTTP response code and HTTP body contents
type RoundTripFn ¶
RoundTripFn inidicates any function that can be passed to RoundTrip it should return HTTP response or error in case of error
type WriterTracer ¶
type WriterTracer struct { // Writer is io.Writer io.Writer // StartTime is a start time of a request StartTime time.Time // EndTime is end time of a request EndTime time.Time // Request contains information about request Request RequestInfo // ResponseState contains response status ResponseStatus string // ResponseError is all about response error ResponseError error }
WriteTracer is a request tracer that outputs collected stats into the specified io.Writer
func NewWriterTracer ¶
func NewWriterTracer(w io.Writer) *WriterTracer
NewWriterTracer is a tracer that writes results to io.Writer
func (*WriterTracer) Done ¶
func (t *WriterTracer) Done(re *Response, err error) (*Response, error)
Done is called on a completed request
func (*WriterTracer) Start ¶
func (t *WriterTracer) Start(r *http.Request)
Start is called on start of a request