xhr

package
v0.0.0-...-389821e Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2018 License: BSD-3-Clause, MIT Imports: 3 Imported by: 0

README

js/xhr

Package xhr provides GopherJS bindings for the XMLHttpRequest API.

Install

go get honnef.co/go/js/xhr

Documentation

For documentation, see http://godoc.org/honnef.co/go/js/xhr

Documentation

Overview

Package xhr provides GopherJS bindings for the XMLHttpRequest API.

This package provides two ways of using XHR directly. The first one is via the Request type and the NewRequest function. This way, one can specify all desired details of the request's behaviour (timeout, response format). It also allows access to response details such as the status code. Furthermore, using this way is required if one wants to abort in-flight requests or if one wants to register additional event listeners.

req := xhr.NewRequest("GET", "/endpoint")
req.Timeout = 1000 // one second, in milliseconds
req.ResponseType = "document"
err := req.Send(nil)
if err != nil { handle_error() }
// req.Response will contain a JavaScript Document element that can
// for example be used with the js/dom package.

The other way is via the package function Send, which is a helper that internally constructs a Request and assigns sane defaults to it. It's the easiest way of doing an XHR request that should just return unprocessed data.

data, err := xhr.Send("POST", "/endpoint", []byte("payload here"))
if err != nil { handle_error() }
console.Log("Retrieved data", data)

If you don't need to/want to deal with the underlying details of XHR, you may also just use the net/http.DefaultTransport, which GopherJS replaces with an XHR-enabled version, making this package useless most of the time.

Index

Constants

View Source
const (
	// Open has not been called yet
	Unsent = iota
	// Send has not been called yet
	Opened
	HeadersReceived
	Loading
	Done
)

The possible values of Request.ReadyState.

View Source
const (
	ArrayBuffer = "arraybuffer"
	Blob        = "blob"
	Document    = "document"
	JSON        = "json"
	Text        = "text"
)

The possible values of Request.ResponseType

Variables

View Source
var ErrAborted = errors.New("request aborted")

ErrAborted is the error returned by Send when a request was aborted.

View Source
var ErrFailure = errors.New("send failed")

ErrFailure is the error returned by Send when it failed for a reason other than abortion or timeouts.

The specific reason for the error is unknown because the XHR API does not provide us with any information. One common reason is network failure.

View Source
var ErrTimeout = errors.New("request timed out")

ErrTimeout is the error returned by Send when a request timed out.

Functions

func Send

func Send(method, url string, data []byte) ([]byte, error)

Send constructs a new Request and sends it. The response, if any, is interpreted as binary data and returned as is.

For more control over the request, as well as the option to send types other than []byte, construct a Request yourself.

Only errors of the network layer are treated as errors. HTTP status codes 4xx and 5xx are not treated as errors. In order to check status codes, use NewRequest instead.

Types

type Request

type Request struct {
	*js.Object
	util.EventTarget
	ReadyState      int        `js:"readyState"`
	Response        *js.Object `js:"response"`
	ResponseText    string     `js:"responseText"`
	ResponseType    string     `js:"responseType"`
	ResponseXML     *js.Object `js:"responseXML"`
	Status          int        `js:"status"`
	StatusText      string     `js:"statusText"`
	Timeout         int        `js:"timeout"`
	WithCredentials bool       `js:"withCredentials"`
	// contains filtered or unexported fields
}

Request wraps XMLHttpRequest objects. New instances have to be created with NewRequest. Each instance may only be used for a single request.

To create a request that behaves in the same way as the top-level Send function with regard to handling binary data, use the following:

req := xhr.NewRequest("POST", "http://example.com")
req.ResponseType = xhr.ArrayBuffer
req.Send([]byte("data"))
b := js.Global.Get("Uint8Array").New(req.Response).Interface().([]byte)

func NewRequest

func NewRequest(method, url string) *Request

NewRequest creates a new XMLHttpRequest object, which may be used for a single request.

func (*Request) Abort

func (r *Request) Abort()

Abort will abort the request. The corresponding Send will return ErrAborted, unless the request has already succeeded.

func (*Request) OverrideMimeType

func (r *Request) OverrideMimeType(mimetype string)

OverrideMimeType overrides the MIME type returned by the server.

func (*Request) ResponseHeader

func (r *Request) ResponseHeader(name string) string

ResponseHeader returns the value of the specified header.

func (*Request) ResponseHeaders

func (r *Request) ResponseHeaders() string

ResponseHeaders returns all response headers.

func (*Request) Send

func (r *Request) Send(data interface{}) error

Send sends the request that was prepared with Open. The data argument is optional and can either be a string or []byte payload, or a *js.Object containing an ArrayBufferView, Blob, Document or Formdata.

Send will block until a response was received or an error occured.

Only errors of the network layer are treated as errors. HTTP status codes 4xx and 5xx are not treated as errors. In order to check status codes, use the Request's Status field.

func (*Request) SetRequestHeader

func (r *Request) SetRequestHeader(header, value string)

SetRequestHeader sets a header of the request.

func (*Request) Upload

func (r *Request) Upload() *Upload

Upload returns the XMLHttpRequestUpload object associated with the request. It can be used to register events for tracking the progress of uploads.

type Upload

type Upload struct {
	*js.Object
	util.EventTarget
}

Upload wraps XMLHttpRequestUpload objects.

Jump to

Keyboard shortcuts

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