Documentation ¶
Overview ¶
Package req simplify working with an HTTP requests
Index ¶
- Constants
- Variables
- func SetDialTimeout(timeout float64)
- func SetRequestTimeout(timeout float64)
- func SetUserAgent(app, version string, subs ...string)
- type Engine
- func (e *Engine) Delete(r Request) (*Response, error)
- func (e *Engine) Do(r Request) (*Response, error)
- func (e *Engine) Get(r Request) (*Response, error)
- func (e *Engine) Head(r Request) (*Response, error)
- func (e *Engine) Init() *Engine
- func (e *Engine) Patch(r Request) (*Response, error)
- func (e *Engine) Post(r Request) (*Response, error)
- func (e *Engine) PostFile(r Request, file, fieldName string, extraFields map[string]string) (*Response, error)
- func (e *Engine) Put(r Request) (*Response, error)
- func (e *Engine) SetDialTimeout(timeout float64)
- func (e *Engine) SetRequestTimeout(timeout float64)
- func (e *Engine) SetUserAgent(app, version string, subs ...string)
- type Headers
- type Query
- type Request
- func (r Request) Delete() (*Response, error)
- func (r Request) Do() (*Response, error)
- func (r Request) Get() (*Response, error)
- func (r Request) Head() (*Response, error)
- func (r Request) Patch() (*Response, error)
- func (r Request) Post() (*Response, error)
- func (r Request) PostFile(file, fieldName string, extraFields map[string]string) (*Response, error)
- func (r Request) Put() (*Response, error)
- type RequestError
- type Response
Examples ¶
Constants ¶
const ( ERROR_BODY_ENCODE = 1 ERROR_CREATE_REQUEST = 2 ERROR_SEND_REQUEST = 3 )
Error types
const ( POST = "POST" GET = "GET" PUT = "PUT" HEAD = "HEAD" DELETE = "DELETE" PATCH = "PATCH" )
Request method
const ( CONTENT_TYPE_ATOM = "application/atom+xml" CONTENT_TYPE_EDI = "application/EDI-X12" CONTENT_TYPE_EDIFACT = "application/EDIFACT" CONTENT_TYPE_JSON = "application/json" CONTENT_TYPE_JAVASCRIPT = "application/javascript" CONTENT_TYPE_OCTET_STREAM = "application/octet-stream" CONTENT_TYPE_PDF = "application/pdf" CONTENT_TYPE_POSTSCRIPT = "application/postscript" CONTENT_TYPE_SOAP = "application/soap+xml" CONTENT_TYPE_WOFF = "application/font-woff" CONTENT_TYPE_XHTML = "application/xhtml+xml" CONTENT_TYPE_DTD = "application/xml-dtd" CONTENT_TYPE_XOP = "application/xop+xml" CONTENT_TYPE_ZIP = "application/zip" CONTENT_TYPE_GZIP = "application/gzip" CONTENT_TYPE_BITTORRENT = "application/x-bittorrent" CONTENT_TYPE_TEX = "application/x-tex" CONTENT_TYPE_BASIC = "audio/basic" CONTENT_TYPE_L24 = "audio/L24" CONTENT_TYPE_MP4_AUDIO = "audio/mp4" CONTENT_TYPE_AAC = "audio/aac" CONTENT_TYPE_MPEG_AUDIO = "audio/mpeg" CONTENT_TYPE_OGG_AUDIO = "audio/ogg" CONTENT_TYPE_VORBIS = "audio/vorbis" CONTENT_TYPE_WMA = "audio/x-ms-wma" CONTENT_TYPE_WAX = "audio/x-ms-wax" CONTENT_TYPE_REALAUDIO = "audio/vnd.rn-realaudio" CONTENT_TYPE_WAV = "audio/vnd.wave" CONTENT_TYPE_WEBM_AUDIO = "audio/webm" CONTENT_TYPE_GIF = "image/gif" CONTENT_TYPE_JPEG = "image/jpeg" CONTENT_TYPE_PJPEG = "image/pjpeg" CONTENT_TYPE_PNG = "image/png" CONTENT_TYPE_SVG = "image/svg+xml" CONTENT_TYPE_TIFF = "image/tiff" CONTENT_TYPE_ICON = "image/vnd.microsoft.icon" CONTENT_TYPE_WBMP = "image/vnd.wap.wbmp" CONTENT_TYPE_HTTP = "message/http" CONTENT_TYPE_IMDN = "message/imdn+xml" CONTENT_TYPE_PARTIAL = "message/partial" CONTENT_TYPE_RFC822 = "message/rfc822" CONTENT_TYPE_EXAMPLE = "model/example" CONTENT_TYPE_IGES = "model/iges" CONTENT_TYPE_MESH = "model/mesh" CONTENT_TYPE_VRML = "model/vrml" CONTENT_TYPE_MIXED = "multipart/mixed" CONTENT_TYPE_ALTERNATIVE = "multipart/alternative" CONTENT_TYPE_RELATED = "multipart/related" CONTENT_TYPE_FORM_DATA = "multipart/form-data" CONTENT_TYPE_SIGNED = "multipart/signed" CONTENT_TYPE_ENCRYPTED = "multipart/encrypted" CONTENT_TYPE_CSS = "text/css" CONTENT_TYPE_CSV = "text/csv" CONTENT_TYPE_HTML = "text/html" CONTENT_TYPE_PLAIN = "text/plain" CONTENT_TYPE_PHP = "text/php" CONTENT_TYPE_XML = "text/xml" CONTENT_TYPE_MPEG_VIDEO = "video/mpeg" CONTENT_TYPE_MP4_VIDEO = "video/mp4" CONTENT_TYPE_OGG_VIDEO = "video/ogg" CONTENT_TYPE_QUICKTIME = "video/quicktime" CONTENT_TYPE_WEBM_VIDEO = "video/webm" CONTENT_TYPE_WMV = "video/x-ms-wmv" CONTENT_TYPE_FLV = "video/x-flv" CONTENT_TYPE_3GPP = "video/3gpp" CONTENT_TYPE_3GPP2 = "video/3gpp2" )
Content types
const ( STATUS_CONTINUE = 100 // RFC 7231, 6.2.1 STATUS_SWITCHING_PROTOCOLS = 101 // RFC 7231, 6.2.2 STATUS_PROCESSING = 102 // RFC 2518, 10.1 STATUS_OK = 200 // RFC 7231, 6.3.1 STATUS_CREATED = 201 // RFC 7231, 6.3.2 STATUS_ACCEPTED = 202 // RFC 7231, 6.3.3 STATUS_NON_AUTHORITATIVE_INFO = 203 // RFC 7231, 6.3.4 STATUS_NO_CONTENT = 204 // RFC 7231, 6.3.5 STATUS_RESET_CONTENT = 205 // RFC 7231, 6.3.6 STATUS_PARTIAL_CONTENT = 206 // RFC 7233, 4.1 STATUS_MULTI_STATUS = 207 // RFC 4918, 11.1 STATUS_ALREADY_REPORTED = 208 // RFC 5842, 7.1 STATUS_IMUSED = 226 // RFC 3229, 10.4.1 STATUS_MULTIPLE_CHOICES = 300 // RFC 7231, 6.4.1 STATUS_MOVED_PERMANENTLY = 301 // RFC 7231, 6.4.2 STATUS_FOUND = 302 // RFC 7231, 6.4.3 STATUS_SEE_OTHER = 303 // RFC 7231, 6.4.4 STATUS_NOT_MODIFIED = 304 // RFC 7232, 4.1 STATUS_USE_PROXY = 305 // RFC 7231, 6.4.5 STATUS_TEMPORARY_REDIRECT = 307 // RFC 7231, 6.4.7 STATUS_PERMANENT_REDIRECT = 308 // RFC 7538, 3 STATUS_BAD_REQUEST = 400 // RFC 7231, 6.5.1 STATUS_UNAUTHORIZED = 401 // RFC 7235, 3.1 STATUS_PAYMENT_REQUIRED = 402 // RFC 7231, 6.5.2 STATUS_FORBIDDEN = 403 // RFC 7231, 6.5.3 STATUS_NOT_FOUND = 404 // RFC 7231, 6.5.4 STATUS_METHOD_NOT_ALLOWED = 405 // RFC 7231, 6.5.5 STATUS_NOT_ACCEPTABLE = 406 // RFC 7231, 6.5.6 STATUS_PROXY_AUTH_REQUIRED = 407 // RFC 7235, 3.2 STATUS_REQUEST_TIMEOUT = 408 // RFC 7231, 6.5.7 STATUS_CONFLICT = 409 // RFC 7231, 6.5.8 STATUS_GONE = 410 // RFC 7231, 6.5.9 STATUS_LENGTH_REQUIRED = 411 // RFC 7231, 6.5.10 STATUS_PRECONDITION_FAILED = 412 // RFC 7232, 4.2 STATUS_REQUEST_ENTITY_TOO_LARGE = 413 // RFC 7231, 6.5.11 STATUS_REQUEST_URITOO_LONG = 414 // RFC 7231, 6.5.12 STATUS_UNSUPPORTED_MEDIA_TYPE = 415 // RFC 7231, 6.5.13 STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416 // RFC 7233, 4.4 STATUS_EXPECTATION_FAILED = 417 // RFC 7231, 6.5.14 STATUS_TEAPOT = 418 // RFC 7168, 2.3.3 STATUS_UNPROCESSABLE_ENTITY = 422 // RFC 4918, 11.2 STATUS_LOCKED = 423 // RFC 4918, 11.3 STATUS_FAILED_DEPENDENCY = 424 // RFC 4918, 11.4 STATUS_UPGRADE_REQUIRED = 426 // RFC 7231, 6.5.15 STATUS_PRECONDITION_REQUIRED = 428 // RFC 6585, 3 STATUS_TOO_MANY_REQUESTS = 429 // RFC 6585, 4 STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE = 431 // RFC 6585, 5 STATUS_UNAVAILABLE_FOR_LEGAL_REASONS = 451 // RFC 7725, 3 STATUS_INTERNAL_SERVER_ERROR = 500 // RFC 7231, 6.6.1 STATUS_NOT_IMPLEMENTED = 501 // RFC 7231, 6.6.2 STATUS_BAD_GATEWAY = 502 // RFC 7231, 6.6.3 STATUS_SERVICE_UNAVAILABLE = 503 // RFC 7231, 6.6.4 STATUS_GATEWAY_TIMEOUT = 504 // RFC 7231, 6.6.5 STATUS_HTTPVERSION_NOT_SUPPORTED = 505 // RFC 7231, 6.6.6 STATUS_VARIANT_ALSO_NEGOTIATES = 506 // RFC 2295, 8.1 STATUS_INSUFFICIENT_STORAGE = 507 // RFC 4918, 11.5 STATUS_LOOP_DETECTED = 508 // RFC 5842, 7.2 STATUS_NOT_EXTENDED = 510 // RFC 2774, 7 STATUS_NETWORK_AUTHENTICATION_REQUIRED = 511 // RFC 6585, 6 )
Status codes
const USER_AGENT = "go-ek-req"
USER_AGENT is default user agent
Variables ¶
var ( // ErrNilEngine is returned if engine struct is nil ErrNilEngine = RequestError{ERROR_CREATE_REQUEST, "Engine is nil"} // ErrNilClient is returned if client struct is nil ErrNilClient = RequestError{ERROR_CREATE_REQUEST, "Engine.Client is nil"} // ErrNilTransport is returned if transport is nil ErrNilTransport = RequestError{ERROR_CREATE_REQUEST, "Engine.Transport is nil"} // ErrNilDialer is returned if dialer is nil ErrNilDialer = RequestError{ERROR_CREATE_REQUEST, "Engine.Dialer is nil"} // ErrNilResponse is returned if response is nil ErrNilResponse = RequestError{ERROR_CREATE_REQUEST, "Response is nil"} // ErrEmptyURL is returned if given URL is empty ErrEmptyURL = RequestError{ERROR_CREATE_REQUEST, "URL property can't be empty and must be set"} // ErrUnsupportedScheme is returned if given URL contains unsupported scheme ErrUnsupportedScheme = RequestError{ERROR_CREATE_REQUEST, "Unsupported scheme in URL"} )
var Global = &Engine{
dialTimeout: 10.0,
}
Global is global engine used by default for Request.Do, Request.Get, Request.Post, Request.Put, Request.Patch, Request.Head and Request.Delete methods
Functions ¶
func SetDialTimeout ¶
func SetDialTimeout(timeout float64)
SetDialTimeout sets dial timeout for global engine
func SetRequestTimeout ¶
func SetRequestTimeout(timeout float64)
SetRequestTimeout sets request timeout for global engine
func SetUserAgent ¶
SetUserAgent sets user agent based on app name and version for global engine
Types ¶
type Engine ¶
type Engine struct { UserAgent string // UserAgent is default user-agent used for all requests Dialer *net.Dialer // Dialer is default dialer struct Transport *http.Transport // Transport is default transport struct Client *http.Client // Client is default client struct // contains filtered or unexported fields }
Engine is request engine
func (*Engine) PostFile ¶
func (e *Engine) PostFile(r Request, file, fieldName string, extraFields map[string]string) (*Response, error)
PostFile sends multipart POST request with file data
func (*Engine) SetDialTimeout ¶
SetDialTimeout sets dial timeout
func (*Engine) SetRequestTimeout ¶
SetRequestTimeout sets request timeout
func (*Engine) SetUserAgent ¶
SetUserAgent sets user agent based on app name and version
type Request ¶
type Request struct { Method string // Request method URL string // Request URL Query Query // Map with query params Body any // Request body Headers Headers // Map with headers ContentType string // Content type header Accept string // Accept header BasicAuthUsername string // Basic auth username BasicAuthPassword string // Basic auth password AutoDiscard bool // Automatically discard all responses with status code != 200 FollowRedirect bool // Follow redirect Close bool // Close indicates whether to close the connection after sending request }
Request is basic struct
func (Request) Do ¶
Do sends request and process response
Example ¶
var response = struct { User string `json:"user"` ID int `json:"id"` Balance float64 `json:"balance"` }{} // Configure global engine SetUserAgent("my-supper-app", "1.0") SetDialTimeout(30.0) SetRequestTimeout(30.0) resp, err := Request{ Method: GET, URL: "https://my.domain.com", Query: Query{ "name": "Bob", "id": 120, "progress": 12.34, }, Headers: Headers{ "My-Suppa-Header": "Test", }, ContentType: CONTENT_TYPE_JSON, }.Do() if err != nil { fmt.Printf("Error: %v\n", err) } // print status code fmt.Printf("Status code: %d\n", resp.StatusCode) // decode JSON encoded response err = resp.JSON(response) if err != nil { fmt.Printf("Error: %v\n", err) } // print response data fmt.Printf( "User: %s ID: %d Balance: %f\n", response.User, response.ID, response.Balance, )
Output:
func (Request) Get ¶
Get sends GET request and process response
Example ¶
var response = struct { User string `json:"user"` ID int `json:"id"` Balance float64 `json:"balance"` }{} resp, err := Request{URL: "https://my.domain.com"}.Get() if err != nil { fmt.Printf("Error: %v\n", err) } // decode json encoded response err = resp.JSON(response) if err != nil { fmt.Printf("Error: %v\n", err) } // print response data fmt.Printf( "User: %s ID: %d Balance: %f\n", response.User, response.ID, response.Balance, )
Output:
func (Request) Post ¶
Post sends POST request and process response
Example ¶
var request = struct { UserID int `json:"user_id"` }{ UserID: 1234, } var response = struct { User string `json:"user"` ID int `json:"id"` Balance float64 `json:"balance"` }{} // send post request with basic auth resp, err := Request{ URL: "https://my.domain.com", Body: request, Accept: CONTENT_TYPE_JSON, ContentType: CONTENT_TYPE_JSON, BasicAuthUsername: "someuser", BasicAuthPassword: "somepass", AutoDiscard: true, }.Post() if err != nil { fmt.Printf("Error: %v\n", err) } // decode JSON encoded response err = resp.JSON(response) if err != nil { fmt.Printf("Error: %v\n", err) } // print response data fmt.Printf( "User: %s ID: %d Balance: %f\n", response.User, response.ID, response.Balance, )
Output:
func (Request) PostFile ¶
PostFile sends multipart POST request with file data
Example ¶
extraFields := map[string]string{ "user": "john", "desc": "My photo", } // send multipart request with image resp, err := Request{ URL: "https://my.domain.com", }.PostFile("/tmp/image.jpg", "file", extraFields) if err != nil { fmt.Printf("Error: %v\n", err) return } if resp.StatusCode != 200 { fmt.Printf("Can't upload file: %v\n", err) return } fmt.Println("File successfully uploaded!")
Output:
type RequestError ¶
type RequestError struct {
// contains filtered or unexported fields
}
RequestError is error struct