xhr

package module
v0.0.0-...-31387d8 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2020 License: MIT Imports: 5 Imported by: 0

README

js/xhr

Package xhr provides GopherJS bindings for the XMLHttpRequest API.

Install

go get github.com/rocketlaunchr/gopherjs-xhr

Usage

node.js

Install npm package xhr2

File: imports.inc.js

global.XMLHttpRequest = require('xhr2'); 
node.js and browser
import (
	"context"

	xhr "github.com/rocketlaunchr/gopherjs-xhr"
	"github.com/gopherjs/gopherjs/js"
	"github.com/rocketlaunchr/react/forks/encoding/json"
)

req := xhr.NewRequest("POST", reqURL)
req.ResponseType = xhr.Text // Returns response as string
req.SetRequestHeader("Content-Type", xhr.ApplicationForm)


postBody := NewParams(js.M{"setting": 4})

err := req.Send(context.Background(), postBody.String())
if err != nil {
	// Could not connect to internet???
	// Unfortunately XMLHttpRequest does not provide nuanced reasons.
	return
}

if !req.IsStatus2xx() {
	// Something went wrong
	return
}

// Unmarshal json response here using encoding/json. Otherwise set req.ResponseType = "json".
err = json.Unmarshal(req.ResponseBytes(), &sb)

Documentation

For documentation, see http://godoc.org/github.com/rocketlaunchr/gopherjs-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.ResponseType = "document"
err := req.Send(ctx, 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(ctx, "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

View Source
const (
	// ApplicationForm is a common "Content-Type" used by forms.
	ApplicationForm = "application/x-www-form-urlencoded"
	// ApplicationJSON is a common "Content-Type" used when making a POST request.
	ApplicationJSON = "application/json"
	// TextPlain is a common "Content-Type".
	TextPlain = "text/plain"
)

Variables

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 MultipartFormData = func(boundary string) string {
	return "multipart/form-data;boundary=\"" + boundary + "\""
}

MultipartFormData is a common "Content-Type" when transferring files in a POST request.

Functions

func Send

func Send(ctx context.Context, 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.

func ToJSON

func ToJSON(obj interface{}) string

ToJSON will convert an object or map into a JSON string.

Types

type Params

type Params struct {
	*js.Object
}

Params represents a URLSearchParams object

func NewParams

func NewParams(kv ...js.M) *Params

NewParams returns a new URLSearchParams object.

func (*Params) Append

func (p *Params) Append(kv js.M)

Appends a specified key/value pair as a new search parameter.

func (*Params) String

func (p *Params) String() string

String returns a string containing a query string suitable for use in a URL.

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"`
	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(ctx, []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) IsStatus2xx

func (r *Request) IsStatus2xx() bool

IsStatus2xx returns true if the request returned a 2xx status code.

func (*Request) IsStatus4xx

func (r *Request) IsStatus4xx() bool

IsStatus4xx returns true if the request returned a 4xx status code.

func (*Request) IsStatus5xx

func (r *Request) IsStatus5xx() bool

IsStatus5xx returns true if the request returned a 5xx status code.

func (*Request) OverrideMimeType

func (r *Request) OverrideMimeType(mimetype string)

OverrideMimeType overrides the MIME type returned by the server.

func (*Request) ResponseBytes

func (r *Request) ResponseBytes() []byte

ResponseBytes returns the ResponseText as a slice of bytes.

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(ctx context.Context, 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