HTTPRequest

package
v0.0.0-...-357ca8a Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2025 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

A node with the ability to send HTTP requests. Uses HTTPClient internally.

Can be used to make HTTP requests, i.e. download or upload files or web content via HTTP.

Warning: See the notes and warnings on HTTPClient for limitations, especially regarding TLS security.

Note: When exporting to Android, make sure to enable the INTERNET permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android.

Example: Contact a REST API and print one of its returned fields:

package main

import (
	"encoding/json"

	"graphics.gd/classdb/Engine"
	"graphics.gd/classdb/HTTPClient"
	"graphics.gd/classdb/HTTPRequest"
	"graphics.gd/classdb/Node"
	"graphics.gd/variant/Signal"
)

type ExampleHTTP struct {
	Node.Extension[ExampleHTTP]
}

func (n *ExampleHTTP) Ready() {
	// Create an HTTP request node and connect its completion signal.
	var httpRequest = HTTPRequest.New()
	n.AsNode().AddChild(httpRequest.AsNode())
	httpRequest.OnRequestCompleted(func(result HTTPRequest.Result, response_code int, headers []string, body []byte) {
		var Response struct {
			Headers map[string]string
		}
		json.Unmarshal(body, &Response)
		// Will print the user agent string used by the HTTPRequest node (as recognized by httpbin.org).
		println(Response.Headers["User-Agent"])

		// Perform a POST request. The URL below returns JSON as of writing.
		body, _ = json.Marshal(map[string]string{"name": "Godette"})
		var err = httpRequest.MoreArgs().Request("https://httpbin.org/post", nil, HTTPClient.MethodPost, string(body))
		if err != nil {
			Engine.Raise(err)
		}
	}, Signal.OneShot)
	// Perform a GET request. The URL below returns JSON as of writing.
	var err = httpRequest.MoreArgs().Request("https://httpbin.org/get", nil, HTTPClient.MethodGet, "")
	if err != nil {
		Engine.Raise(err)
	}
	// Note: Don't make simultaneous requests using a single HTTPRequest node.
}

Example: Load an image using HTTPRequest and display it:

package main

import (
	"errors"

	"graphics.gd/classdb/Engine"
	"graphics.gd/classdb/HTTPRequest"
	"graphics.gd/classdb/Image"
	"graphics.gd/classdb/ImageTexture"
	"graphics.gd/classdb/Node"
	"graphics.gd/classdb/TextureRect"
	"graphics.gd/variant/Signal"
)

type ExampleDownloadImage struct {
	Node.Extension[ExampleDownloadImage]
}

func (n ExampleDownloadImage) Ready() {
	var http_request = HTTPRequest.New()
	n.AsNode().AddChild(http_request.AsNode())
	http_request.AsHTTPRequest().OnRequestCompleted(func(result HTTPRequest.Result, response_code int, headers []string, body []byte) {
		if result != HTTPRequest.ResultSuccess {
			Engine.Raise(errors.New("Image couldn't be downloaded. Try a different image."))
		}
		var image = Image.New()
		var err = image.LoadPngFromBuffer(body)
		if err != nil {
			Engine.Raise(errors.New("Couldn't load the image."))
		}
		var texture = ImageTexture.CreateFromImage(image)

		// Display the image in a TextureRect node.
		var texture_rect = TextureRect.New()
		texture_rect.AsTextureRect().SetTexture(texture.AsTexture2D())
		n.AsNode().AddChild(texture_rect.AsNode())
	}, Signal.OneShot)
	// Perform the HTTP request. The URL below returns a PNG image as of writing.
	var error = http_request.Request("https://placehold.co/512")
	if error != nil {
		panic("An error occurred in the HTTP request.")
	}
}

Note: HTTPRequest nodes will automatically handle decompression of response bodies. An Accept-Encoding header will be automatically added to each of your requests, unless one is already specified. Any response with a Content-Encoding: gzip header will automatically be decompressed and delivered to you as uncompressed bytes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Advanced

type Advanced = class

Advanced exposes a 1:1 low-level instance of the class, undocumented, for those who know what they are doing.

type Any

type Any interface {
	gd.IsClass
	AsHTTPRequest() Instance
}

type Expanded

type Expanded = MoreArgs

type Extension

type Extension[T gdclass.Interface] struct{ gdclass.Extension[T, Instance] }

Extension can be embedded in a new struct to create an extension of this class. T should be the type that is embedding this Extension

func (*Extension[T]) AsHTTPRequest

func (self *Extension[T]) AsHTTPRequest() Instance

func (*Extension[T]) AsNode

func (self *Extension[T]) AsNode() Node.Instance

func (*Extension[T]) AsObject

func (self *Extension[T]) AsObject() [1]gd.Object

type ID

type ID Object.ID

ID is a typed object ID (reference) to an instance of this class, use it to store references to objects with unknown lifetimes, as an ID will not panic on use if the underlying object has been destroyed.

func (ID) Instance

func (id ID) Instance() (Instance, bool)

type Instance

type Instance [1]gdclass.HTTPRequest

Instance of the class with convieniently typed arguments and results.

var Nil Instance

Nil is a nil/null instance of the class. Equivalent to the zero value.

func New

func New() Instance

func (Instance) AcceptGzip

func (self Instance) AcceptGzip() bool

If true, this header will be added to each request: Accept-Encoding: gzip, deflate telling servers that it's okay to compress response bodies.

Any Response body declaring a Content-Encoding of either gzip or deflate will then be automatically decompressed, and the uncompressed bytes will be delivered via OnRequestCompleted.

If the user has specified their own Accept-Encoding header, then no header will be added regardless of AcceptGzip.

If false no header will be added, and no decompression will be performed on response bodies. The raw bytes of the response body will be returned via OnRequestCompleted.

func (Instance) AsHTTPRequest

func (self Instance) AsHTTPRequest() Instance

func (Instance) AsNode

func (self Instance) AsNode() Node.Instance

func (Instance) AsObject

func (self Instance) AsObject() [1]gd.Object

func (Instance) BodySizeLimit

func (self Instance) BodySizeLimit() int

Maximum allowed size for response bodies. If the response body is compressed, this will be used as the maximum allowed size for the decompressed body.

func (Instance) CancelRequest

func (self Instance) CancelRequest()

Cancels the current request.

func (Instance) DownloadChunkSize

func (self Instance) DownloadChunkSize() int

The size of the buffer used and maximum bytes to read per iteration. See HTTPClient.ReadChunkSize.

Set this to a lower value (e.g. 4096 for 4 KiB) when downloading small files to decrease memory usage at the cost of download speeds.

func (Instance) DownloadFile

func (self Instance) DownloadFile() string

The file to download into. Will output any received file into it.

func (Instance) GetBodySize

func (self Instance) GetBodySize() int

Returns the response body length.

Note: Some Web servers may not send a body length. In this case, the value returned will be -1. If using chunked transfer encoding, the body length will also be -1.

func (Instance) GetDownloadedBytes

func (self Instance) GetDownloadedBytes() int

Returns the number of bytes this HTTPRequest downloaded.

func (Instance) GetHttpClientStatus

func (self Instance) GetHttpClientStatus() HTTPClient.Status

Returns the current status of the underlying HTTPClient.

func (Instance) ID

func (self Instance) ID() ID

func (Instance) MaxRedirects

func (self Instance) MaxRedirects() int

Maximum number of allowed redirects.

func (Instance) MoreArgs

func (self Instance) MoreArgs() MoreArgs

MoreArgs enables certain functions to be called with additional 'optional' arguments.

func (Instance) OnRequestCompleted

func (self Instance) OnRequestCompleted(cb func(result Result, response_code int, headers []string, body []byte), flags ...Signal.Flags)

Emitted when a request is completed.

func (Instance) Request

func (self Instance) Request(url string) error

Creates request on the underlying HTTPClient. If there is no configuration errors, it tries to connect using HTTPClient.ConnectToHost and passes parameters onto HTTPClient.Request.

Returns [Ok] if request is successfully created. (Does not imply that the server has responded), [ErrUnconfigured] if not in the tree, [ErrBusy] if still processing previous request, [ErrInvalidParameter] if given string is not a valid URL format, or [ErrCantConnect] if not using thread and the HTTPClient cannot connect to host.

Note: When 'method' is [Httpclient.MethodGet], the payload sent via 'request_data' might be ignored by the server or even cause the server to reject the request (check RFC 7231 section 4.3.1 for more details). As a workaround, you can send data as a query string in the URL (see String.UriEncode for an example).

Note: It's recommended to use transport encryption (TLS) and to avoid sending sensitive information (such as login credentials) in HTTP GET URL parameters. Consider using HTTP POST requests or HTTP headers for such information instead.

func (Instance) RequestRaw

func (self Instance) RequestRaw(url string) error

Creates request on the underlying HTTPClient using a raw array of bytes for the request body. If there is no configuration errors, it tries to connect using HTTPClient.ConnectToHost and passes parameters onto HTTPClient.Request.

Returns [Ok] if request is successfully created. (Does not imply that the server has responded), [ErrUnconfigured] if not in the tree, [ErrBusy] if still processing previous request, [ErrInvalidParameter] if given string is not a valid URL format, or [ErrCantConnect] if not using thread and the HTTPClient cannot connect to host.

func (Instance) SetAcceptGzip

func (self Instance) SetAcceptGzip(value bool)

SetAcceptGzip sets the property returned by [IsAcceptingGzip].

func (Instance) SetBodySizeLimit

func (self Instance) SetBodySizeLimit(value int)

SetBodySizeLimit sets the property returned by [GetBodySizeLimit].

func (Instance) SetDownloadChunkSize

func (self Instance) SetDownloadChunkSize(value int)

SetDownloadChunkSize sets the property returned by [GetDownloadChunkSize].

func (Instance) SetDownloadFile

func (self Instance) SetDownloadFile(value string)

SetDownloadFile sets the property returned by [GetDownloadFile].

func (Instance) SetHttpProxy

func (self Instance) SetHttpProxy(host string, port int)

Sets the proxy server for HTTP requests.

The proxy server is unset if 'host' is empty or 'port' is -1.

func (Instance) SetHttpsProxy

func (self Instance) SetHttpsProxy(host string, port int)

Sets the proxy server for HTTPS requests.

The proxy server is unset if 'host' is empty or 'port' is -1.

func (Instance) SetMaxRedirects

func (self Instance) SetMaxRedirects(value int)

SetMaxRedirects sets the property returned by [GetMaxRedirects].

func (*Instance) SetObject

func (self *Instance) SetObject(obj [1]gd.Object) bool

func (Instance) SetTimeout

func (self Instance) SetTimeout(value Float.X)

SetTimeout sets the property returned by [GetTimeout].

func (Instance) SetTlsOptions

func (self Instance) SetTlsOptions(client_options TLSOptions.Instance)

Sets the TLSOptions to be used when connecting to an HTTPS server. See TLSOptions.Client.

func (Instance) SetUseThreads

func (self Instance) SetUseThreads(value bool)

SetUseThreads sets the property returned by [IsUsingThreads].

func (Instance) Timeout

func (self Instance) Timeout() Float.X

The duration to wait in seconds before a request times out. If Timeout is set to 0.0 then the request will never time out. For simple requests, such as communication with a REST API, it is recommended that Timeout is set to a value suitable for the server response time (e.g. between 1.0 and 10.0). This will help prevent unwanted timeouts caused by variation in server response times while still allowing the application to detect when a request has timed out. For larger requests such as file downloads it is suggested the Timeout be set to 0.0, disabling the timeout functionality. This will help to prevent large transfers from failing due to exceeding the timeout value.

func (Instance) UseThreads

func (self Instance) UseThreads() bool

If true, multithreading is used to improve performance.

func (Instance) Virtual

func (self Instance) Virtual(name string) reflect.Value

type MoreArgs

type MoreArgs [1]gdclass.HTTPRequest

MoreArgs is a container for Instance functions with additional 'optional' arguments.

func (MoreArgs) Request

func (self MoreArgs) Request(url string, custom_headers []string, method HTTPClient.Method, request_data string) error

Creates request on the underlying HTTPClient. If there is no configuration errors, it tries to connect using HTTPClient.ConnectToHost and passes parameters onto HTTPClient.Request.

Returns [Ok] if request is successfully created. (Does not imply that the server has responded), [ErrUnconfigured] if not in the tree, [ErrBusy] if still processing previous request, [ErrInvalidParameter] if given string is not a valid URL format, or [ErrCantConnect] if not using thread and the HTTPClient cannot connect to host.

Note: When 'method' is [Httpclient.MethodGet], the payload sent via 'request_data' might be ignored by the server or even cause the server to reject the request (check RFC 7231 section 4.3.1 for more details). As a workaround, you can send data as a query string in the URL (see String.UriEncode for an example).

Note: It's recommended to use transport encryption (TLS) and to avoid sending sensitive information (such as login credentials) in HTTP GET URL parameters. Consider using HTTP POST requests or HTTP headers for such information instead.

func (MoreArgs) RequestRaw

func (self MoreArgs) RequestRaw(url string, custom_headers []string, method HTTPClient.Method, request_data_raw []byte) error

Creates request on the underlying HTTPClient using a raw array of bytes for the request body. If there is no configuration errors, it tries to connect using HTTPClient.ConnectToHost and passes parameters onto HTTPClient.Request.

Returns [Ok] if request is successfully created. (Does not imply that the server has responded), [ErrUnconfigured] if not in the tree, [ErrBusy] if still processing previous request, [ErrInvalidParameter] if given string is not a valid URL format, or [ErrCantConnect] if not using thread and the HTTPClient cannot connect to host.

type Result

type Result int //gd:HTTPRequest.Result
const (
	// Request successful.
	ResultSuccess Result = 0
	// Request failed due to a mismatch between the expected and actual chunked body size during transfer. Possible causes include network errors, server misconfiguration, or issues with chunked encoding.
	ResultChunkedBodySizeMismatch Result = 1
	// Request failed while connecting.
	ResultCantConnect Result = 2
	// Request failed while resolving.
	ResultCantResolve Result = 3
	// Request failed due to connection (read/write) error.
	ResultConnectionError Result = 4
	// Request failed on TLS handshake.
	ResultTlsHandshakeError Result = 5
	// Request does not have a response (yet).
	ResultNoResponse Result = 6
	// Request exceeded its maximum size limit, see [BodySizeLimit].
	//
	// [BodySizeLimit]: https://pkg.go.dev/graphics.gd/classdb/#Instance.BodySizeLimit
	ResultBodySizeLimitExceeded Result = 7
	// Request failed due to an error while decompressing the response body. Possible causes include unsupported or incorrect compression format, corrupted data, or incomplete transfer.
	ResultBodyDecompressFailed Result = 8
	// Request failed (currently unused).
	ResultRequestFailed Result = 9
	// HTTPRequest couldn't open the download file.
	ResultDownloadFileCantOpen Result = 10
	// HTTPRequest couldn't write to the download file.
	ResultDownloadFileWriteError Result = 11
	// Request reached its maximum redirect limit, see [MaxRedirects].
	//
	// [MaxRedirects]: https://pkg.go.dev/graphics.gd/classdb/#Instance.MaxRedirects
	ResultRedirectLimitReached Result = 12
	// Request failed due to a timeout. If you expect requests to take a long time, try increasing the value of [Timeout] or setting it to 0.0 to remove the timeout completely.
	//
	// [Timeout]: https://pkg.go.dev/graphics.gd/classdb/#Instance.Timeout
	ResultTimeout Result = 13
)

Jump to

Keyboard shortcuts

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