cronet

package module
v0.0.0-...-2a8c6ce Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: GPL-2.0 Imports: 33 Imported by: 1

README

cronet-go

Reference

Go bindings for naiveproxy.

Supported Platforms

Target OS CPU
android/386 android x86
android/amd64 android x64
android/arm android arm
android/arm64 android arm64
darwin/amd64 mac x64
darwin/arm64 mac arm64
ios/arm64 ios arm64
ios/amd64 ios amd64
linux/386 linux x86
linux/amd64 linux x64
linux/arm linux arm
linux/arm64 linux arm64
linux/loong64 linux loong64
windows/amd64 win x64
windows/arm64 win arm64

System Requirements

Platform Minimum Version
macOS 12.0 (Monterey)
iOS/tvOS 15.0
Windows 10
Android 5.0 (API 21)
Linux (glibc) glibc 2.31 (loong64: 2.36)
Linux (musl) any (loong64: 1.2.5)

Downstream Build Requirements

Platform Requirements Go Build Flags
Linux (glibc) Chromium toolchain -
Linux (musl) Chromium toolchain -tags with_musl
macOS / iOS macOS Xcode -
iOS simulator/ tvOS / tvOS simulator macOS Xcode + SagerNet/gomobile -
Windows - CGO_ENABLED=0 -tags with_purego
Android Android NDK -

Linux Build instructions

git clone --recursive --depth=1 https://github.com/dkrhodes/cronet-go.git
cd cronet-go
go run ./cmd/build-naive --target=linux/amd64 download-toolchain
#go run ./cmd/build-naive --target=linux/amd64 --libc=musl download-toolchain

# Outputs CC, CXX, and CGO_LDFLAGS=-fuse-ld=lld
export $(go run ./cmd/build-naive --target=linux/amd64 env)
#export $(go run ./cmd/build-naive --target=linux/amd64 --libc=musl env)

cd /path/to/your/project
go build
# go build -tags with_musl
Directories to cache
- cronet-go/naiveproxy/src/third_party/llvm-build/
- cronet-go/naiveproxy/src/gn/out/
- cronet-go/naiveproxy/src/chrome/build/pgo_profiles/
- cronet-go/naiveproxy/src/out/sysroot-build/

Windows / purego Build Instructions

For Windows or pure Go builds (no CGO), you need to distribute the dynamic library alongside your binary.

Download Library

Download libcronet.dll (Windows) or libcronet.so (Linux) from GitHub Releases.

Build with purego
# Windows (purego is required)
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -tags with_purego -o myapp.exe

# Linux with purego (optional, for dynamic linking)
CGO_ENABLED=0 go build -tags with_purego -o myapp
Distribution

Place the library file in the same directory as your executable:

  • Windows: libcronet.dll
  • Linux: libcronet.so
For Downstream Developers

If you need to programmatically extract libraries from Go module dependencies (e.g., for CI/CD pipelines):

go run github.com/dkrhodes/cronet-go/cmd/build-naive@latest extract-lib --target windows/amd64 -n libcronet_amd64.dll
go run github.com/dkrhodes/cronet-go/cmd/build-naive@latest extract-lib --target linux/amd64 -n libcronet_amd64.so

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BidirectionalConn

type BidirectionalConn struct {
	// contains filtered or unexported fields
}

func (*BidirectionalConn) Close

func (c *BidirectionalConn) Close() error

func (*BidirectionalConn) Done

func (c *BidirectionalConn) Done() <-chan struct{}

func (*BidirectionalConn) Err

func (c *BidirectionalConn) Err() error

func (*BidirectionalConn) LocalAddr

func (c *BidirectionalConn) LocalAddr() net.Addr

func (*BidirectionalConn) Read

func (c *BidirectionalConn) Read(p []byte) (n int, err error)

func (*BidirectionalConn) RemoteAddr

func (c *BidirectionalConn) RemoteAddr() net.Addr

func (*BidirectionalConn) SetDeadline

func (c *BidirectionalConn) SetDeadline(t time.Time) error

func (*BidirectionalConn) SetReadDeadline

func (c *BidirectionalConn) SetReadDeadline(t time.Time) error

func (*BidirectionalConn) SetWriteDeadline

func (c *BidirectionalConn) SetWriteDeadline(t time.Time) error

func (*BidirectionalConn) Start

func (c *BidirectionalConn) Start(method string, url string, headers map[string]string, priority int, endOfStream bool) error

func (*BidirectionalConn) WaitForHeaders

func (c *BidirectionalConn) WaitForHeaders() (map[string]string, error)

func (*BidirectionalConn) WaitForHeadersContext

func (c *BidirectionalConn) WaitForHeadersContext(ctx context.Context) (map[string]string, error)

func (*BidirectionalConn) Write

func (c *BidirectionalConn) Write(p []byte) (n int, err error)

type BidirectionalStream

type BidirectionalStream struct {
	// contains filtered or unexported fields
}

BidirectionalStream is an opaque object representing a Bidirectional Stream.

func (BidirectionalStream) Cancel

func (c BidirectionalStream) Cancel()

Cancel cancels the stream. Can be called at any time after Start(). The BidirectionalStreamCallback.OnCanceled() method will be invoked when cancellation is complete and no further callback methods will be invoked. If the stream has completed or has not started, calling Cancel() has no effect and BidirectionalStreamCallback.OnCanceled() will not be invoked. At most one callback method may be invoked after Cancel() has completed.

func (BidirectionalStream) DelayRequestHeadersUntilFlush

func (c BidirectionalStream) DelayRequestHeadersUntilFlush(delay bool)

DelayRequestHeadersUntilFlush delays sending request headers until Flush() is called. This flag is currently only respected when QUIC is negotiated. When true, QUIC will send request header frame along with data frame(s) as a single packet when possible.

func (BidirectionalStream) Destroy

func (c BidirectionalStream) Destroy() bool

Destroy destroys stream object. Destroy could be called from any thread, including network thread, but is posted, so |stream| is valid until calling task is complete. The destroy operation is asynchronous - callbacks may still be invoked after this returns. The stream is marked as destroyed and callbacks will silently return.

func (BidirectionalStream) DisableAutoFlush

func (c BidirectionalStream) DisableAutoFlush(disable bool)

DisableAutoFlush disables or enables auto flush. By default, data is flushed after every Write(). If the auto flush is disabled, the client should explicitly call Flush() to flush the data.

func (BidirectionalStream) Flush

func (c BidirectionalStream) Flush()

Flush Flushes pending writes. This method should not be called before invocation of BidirectionalStreamCallback.OnStreamReady() method. For each previously called Write() a corresponding OnWriteCompleted() callback will be invoked when the buffer is sent.BidirectionalStream

func (BidirectionalStream) Read

func (c BidirectionalStream) Read(buffer []byte) int

Read reads response data into |buffer|. Must only be called at most once in response to each invocation of the OnStreamReady()/OnResponseHeaderReceived() and OnReadCompleted() methods of the BidirectionalStreamCallback. Each call will result in an invocation of the callback's OnReadCompleted() method if data is read, or its OnFailed() method if there's an error. The callback's OnSucceeded() method is also invoked if there is no more data to read and |end_of_stream| was previously sent.

func (BidirectionalStream) Start

func (c BidirectionalStream) Start(method string, url string, headers map[string]string, priority int, endOfStream bool) bool

Start starts the stream by sending request to |url| using |method| and |headers|. If |endOfStream| is true, then no data is expected to be written. The |method| is HTTP verb. noinspection GoDeferInLoop

func (BidirectionalStream) Write

func (c BidirectionalStream) Write(buffer []byte, endOfStream bool) int

Write Writes request data from |buffer| If auto flush is disabled, data will be sent only after Flush() is called. Each call will result in an invocation the callback's BidirectionalStreamCallback.OnWriteCompleted() method if data is sent, or its BidirectionalStreamCallback.OnFailed() method if there's an error. The callback's BidirectionalStreamCallback.OnSucceeded() method is also invoked if |endOfStream| is set and all response data has been read.

type BidirectionalStreamCallback

type BidirectionalStreamCallback interface {
	// OnStreamReady
	// Invoked when the stream is ready for reading and writing.
	// Consumer may call BidirectionalStream.Read() to start reading data.
	// Consumer may call BidirectionalStream.Write() to start writing
	// data.
	OnStreamReady(stream BidirectionalStream)

	// OnResponseHeadersReceived
	// Invoked when initial response headers are received.
	// Consumer must call BidirectionalStream.Read() to start reading.
	// Consumer may call BidirectionalStream.Write() to start writing or
	// close the stream. Contents of |headers| is valid for duration of the call.
	///
	OnResponseHeadersReceived(stream BidirectionalStream, headers map[string]string, negotiatedProtocol string)

	// OnReadCompleted
	// Invoked when data is read into the buffer passed to
	// BidirectionalStream.Read(). Only part of the buffer may be
	// populated. To continue reading, call BidirectionalStream.Read().
	// It may be invoked after on_response_trailers_received()}, if there was
	// pending read data before trailers were received.
	//
	// If |bytesRead| is 0, it means the remote side has signaled that it will
	// send no more data; future calls to BidirectionalStream.Read()
	// will result in the OnReadCompleted() callback or OnSucceeded() callback if
	// BidirectionalStream.Write() was invoked with endOfStream set to
	// true.
	OnReadCompleted(stream BidirectionalStream, bytesRead int)

	// OnWriteCompleted
	// Invoked when all data passed to BidirectionalStream.Write() is
	// sent. To continue writing, call BidirectionalStream.Write().
	OnWriteCompleted(stream BidirectionalStream)

	// OnResponseTrailersReceived
	// Invoked when trailers are received before closing the stream. Only invoked
	// when server sends trailers, which it may not. May be invoked while there is
	// read data remaining in local buffer. Contents of |trailers| is valid for
	// duration of the call.
	OnResponseTrailersReceived(stream BidirectionalStream, trailers map[string]string)

	// OnSucceeded
	// Invoked when there is no data to be read or written and the stream is
	// closed successfully remotely and locally. Once invoked, no further callback
	// methods will be invoked.
	OnSucceeded(stream BidirectionalStream)

	// OnFailed
	// Invoked if the stream failed for any reason after
	// BidirectionalStream.Start(). HTTP/2 error codes are
	// mapped to chrome net error codes. Once invoked, no further callback methods
	// will be invoked.
	OnFailed(stream BidirectionalStream, netError int)

	// OnCanceled
	// Invoked if the stream was canceled via
	// BidirectionalStream.Cancel(). Once invoked, no further callback
	// methods will be invoked.
	OnCanceled(stream BidirectionalStream)
}

BidirectionalStreamCallback Set of callbacks used to receive callbacks from bidirectional stream.

type BidirectionalStreamHeaderArray

type BidirectionalStreamHeaderArray struct {
	// contains filtered or unexported fields
}

BidirectionalStreamHeaderArray is used to pass headers to bidirectional streams.

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

Buffer provided by the application to read and write data.

func NewBuffer

func NewBuffer() Buffer

func NewBufferWith

func NewBufferWith(handler BufferHandler) Buffer

NewBufferWith creates a new Buffer with custom handler (for testing/mocking).

func (Buffer) ClientContext

func (b Buffer) ClientContext() unsafe.Pointer

func (Buffer) Data

func (b Buffer) Data() unsafe.Pointer

Data return raw pointer to |data| owned by this buffer.

func (Buffer) DataSlice

func (b Buffer) DataSlice() []byte

func (Buffer) Destroy

func (b Buffer) Destroy()

func (Buffer) InitWithAlloc

func (b Buffer) InitWithAlloc(size int64)

InitWithAlloc initialize Buffer by allocating buffer of |size|. The content of allocated data is not initialized.

func (Buffer) InitWithDataAndCallback

func (b Buffer) InitWithDataAndCallback(data []byte, callback BufferCallback)

InitWithDataAndCallback initialize Buffer with raw buffer |data| of |size| allocated by the app. The |callback| is invoked when buffer is destroyed.

func (Buffer) SetClientContext

func (b Buffer) SetClientContext(context unsafe.Pointer)

func (Buffer) Size

func (b Buffer) Size() int64

Size return size of data owned by this buffer.

type BufferCallback

type BufferCallback struct {
	// contains filtered or unexported fields
}

BufferCallback is called when the Buffer is destroyed.

func NewBufferCallback

func NewBufferCallback(callbackFunc BufferCallbackFunc) BufferCallback

func (BufferCallback) ClientContext

func (c BufferCallback) ClientContext() unsafe.Pointer

func (BufferCallback) Destroy

func (c BufferCallback) Destroy()

func (BufferCallback) SetClientContext

func (c BufferCallback) SetClientContext(context unsafe.Pointer)

type BufferCallbackFunc

type BufferCallbackFunc func(callback BufferCallback, buffer Buffer)

BufferCallbackFunc is called when the Buffer is destroyed.

type BufferHandler

type BufferHandler interface {
	InitWithDataAndCallback(self Buffer, data unsafe.Pointer, size uint64, callback BufferCallback)
	InitWithAlloc(self Buffer, size uint64)
	GetSize(self Buffer) uint64
	GetData(self Buffer) unsafe.Pointer
}

BufferHandler is an interface for custom Buffer implementations (for testing/mocking).

type DNSResolverFunc

type DNSResolverFunc func(ctx context.Context, request *mDNS.Msg) (response *mDNS.Msg)

DNSResolverFunc resolves a DNS request into a DNS response.

The resolver is used by NaiveClient's optional in-process DNS server. The returned message should be a response to the request; the implementation will normalize the ID and question section as needed.

type DateTime

type DateTime struct {
	// contains filtered or unexported fields
}

DateTime represents a date and time value from cronet.

func NewDateTime

func NewDateTime() DateTime

func (DateTime) Destroy

func (t DateTime) Destroy()

func (DateTime) SetValue

func (t DateTime) SetValue(value time.Time)

SetValue Number of milliseconds since the UNIX epoch.

func (DateTime) Value

func (t DateTime) Value() time.Time

type Dialer

type Dialer func(address string, port uint16) int

Dialer is a callback function for custom TCP connection establishment. address: IP address string (e.g. "1.2.3.4" or "::1") port: Port number Returns: connected socket fd on success, negative net error code on failure. Common error codes:

ERR_CONNECTION_REFUSED (-102)
ERR_CONNECTION_FAILED (-104)
ERR_ADDRESS_UNREACHABLE (-109)
ERR_CONNECTION_TIMED_OUT (-118)

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is an engine to process URLRequest, which uses the best HTTP stack available on the current platform. An instance of this class can be started using StartWithParams.

func NewEngine

func NewEngine() Engine

func NewEngineWith

func NewEngineWith(handler EngineHandler) Engine

NewEngineWith creates a new Engine with custom handler (for testing/mocking).

func (Engine) AddRequestFinishListener

func (e Engine) AddRequestFinishListener(listener URLRequestFinishedInfoListener, executor Executor)

AddRequestFinishListener registers a listener that gets called at the end of each request.

The listener is called on Executor.

The listener is called before URLRequestCallbackHandler.OnCanceled(), URLRequestCallbackHandler.OnFailed() or URLRequestCallbackHandler.OnSucceeded() is called -- note that if Executor runs the listener asynchronously, the actual call to the listener may happen after a URLRequestCallbackHandler method is called.

Listeners are only guaranteed to be called for requests that are started after the listener is added.

Ownership is **not** taken for listener or Executor.

Assuming the listener won't run again (there are no pending requests with the listener attached, either via Engine or UrlRequest), the app may destroy it once its OnRequestFinished() has started, even inside that method.

Similarly, the app may destroy executor in or after OnRequestFinished()}.

It's also OK to destroy executor in or after one of URLRequestCallbackHandler.OnCanceled(), URLRequestCallbackHandler.OnFailed() or URLRequestCallbackHandler.OnSucceeded().

Of course, both of these are only true if listener won't run again and executor isn't being used for anything else that might start running in the future.

@param listener the listener for finished requests. @param executor the executor upon which to run listener.

func (Engine) ClientContext

func (e Engine) ClientContext() unsafe.Pointer

func (Engine) CloseAllConnections

func (e Engine) CloseAllConnections()

CloseAllConnections closes all connections managed by the engine's network session. This includes socket pools, HTTP stream pool, SPDY session pool, and QUIC session pool. Useful for releasing connection-related memory or speeding up engine shutdown.

func (Engine) DefaultUserAgent

func (e Engine) DefaultUserAgent() string

DefaultUserAgent Returns default human-readable version string of the engine. Can be used before StartWithParams() is called.

func (Engine) Destroy

func (e Engine) Destroy()

func (Engine) RemoveRequestFinishListener

func (e Engine) RemoveRequestFinishListener(listener URLRequestFinishedInfoListener)

RemoveRequestFinishListener unregisters a RequestFinishedInfoListener, including its association with its registered Executor.

func (Engine) SetClientContext

func (e Engine) SetClientContext(context unsafe.Pointer)

func (Engine) SetDialer

func (e Engine) SetDialer(dialer Dialer)

SetDialer sets a custom dialer for TCP connections. When set, the engine will use this callback to establish TCP connections instead of the default system socket API. Must be called before StartWithParams(). Pass nil to disable custom dialing.

func (Engine) SetInsecureSkipVerify

func (e Engine) SetInsecureSkipVerify() bool

SetInsecureSkipVerify installs a cert verifier that accepts any server certificate. For testing only. Must be called before StartWithParams().

func (Engine) SetTrustedRootCertificates

func (e Engine) SetTrustedRootCertificates(pemRootCerts string) bool

SetTrustedRootCertificates sets one or more trusted root certificates for this engine. Must be called before StartWithParams(). pemRootCerts is one or more PEM-encoded certificates concatenated into a single string. Returns true if at least one certificate was successfully parsed, false otherwise.

func (Engine) SetUDPDialer

func (e Engine) SetUDPDialer(dialer UDPDialer)

SetUDPDialer sets a custom dialer for UDP sockets. When set, the engine will use this callback to create UDP sockets instead of the default system socket API. Must be called before StartWithParams(). Pass nil to disable custom dialing.

func (Engine) Shutdown

func (e Engine) Shutdown() Result

Shutdown shuts down the Engine if there are no active requests, otherwise returns a failure Result.

Cannot be called on network thread - the thread Cronet calls into Executor on (which is different from the thread the Executor invokes callbacks on). This method blocks until all the Engine's resources have been cleaned up.

func (Engine) StartNetLogToFile

func (e Engine) StartNetLogToFile(fileName string, logAll bool) bool

StartNetLogToFile starts NetLog logging to a file. The NetLog will contain events emitted by all live Engines. The NetLog is useful for debugging. The file can be viewed using a Chrome browser navigated to chrome://net-internals/#import Returns |true| if netlog has started successfully, |false| otherwise. @param fileName the complete file path. It must not be empty. If the file

exists, it is truncated before starting. If actively logging,
this method is ignored.

@param logAll to include basic events, user cookies,

credentials and all transferred bytes in the log. This option presents
a privacy risk, since it exposes the user's credentials, and should
only be used with the user's consent and in situations where the log
won't be public. false to just include basic events.

func (Engine) StartWithParams

func (e Engine) StartWithParams(params EngineParams) Result

StartWithParams starts Engine using given |params|. The engine must be started once and only once before other methods can be used.

func (Engine) StopNetLog

func (e Engine) StopNetLog()

StopNetLog Stops NetLog logging and flushes file to disk. If a logging session is not in progress, this call is ignored. This method blocks until the log is closed to ensure that log file is complete and available.

func (Engine) StreamEngine

func (e Engine) StreamEngine() StreamEngine

func (Engine) Version

func (e Engine) Version() string

Version returns a human-readable version string of the engine.

type EngineHandler

type EngineHandler interface {
	StartWithParams(self Engine, params EngineParams) Result
	StartNetLogToFile(self Engine, fileName string, logAll bool) bool
	StopNetLog(self Engine)
	Shutdown(self Engine) Result
	GetVersionString(self Engine) string
	GetDefaultUserAgent(self Engine) string
	AddRequestFinishedListener(self Engine, listener URLRequestFinishedInfoListener, executor Executor)
	RemoveRequestFinishedListener(self Engine, listener URLRequestFinishedInfoListener)
}

EngineHandler is an interface for custom Engine implementations (for testing/mocking).

type EngineParams

type EngineParams struct {
	// contains filtered or unexported fields
}

EngineParams contains parameters for initializing a Cronet Engine.

func NewEngineParams

func NewEngineParams() EngineParams

func (EngineParams) AcceptLanguage

func (p EngineParams) AcceptLanguage() string

func (EngineParams) AddPublicKeyPins

func (p EngineParams) AddPublicKeyPins(element PublicKeyPins)

AddPublicKeyPins pins a set of public keys for given hosts. See PublicKeyPins for explanation.

func (EngineParams) AddQuicHint

func (p EngineParams) AddQuicHint(element QuicHint)

AddQuicHint add hints that hosts support QUIC.

func (EngineParams) ClearPublicKeyPins

func (p EngineParams) ClearPublicKeyPins()

func (EngineParams) ClearQuicHints

func (p EngineParams) ClearQuicHints()

func (EngineParams) Destroy

func (p EngineParams) Destroy()

func (EngineParams) EnableBrotli

func (p EngineParams) EnableBrotli() bool

func (EngineParams) EnableCheckResult

func (p EngineParams) EnableCheckResult() bool

func (EngineParams) EnableHTTP2

func (p EngineParams) EnableHTTP2() bool

func (EngineParams) EnablePublicKeyPinningBypassForLocalTrustAnchors

func (p EngineParams) EnablePublicKeyPinningBypassForLocalTrustAnchors() bool

func (EngineParams) EnableQuic

func (p EngineParams) EnableQuic() bool

func (EngineParams) ExperimentalOptions

func (p EngineParams) ExperimentalOptions() string

func (EngineParams) HTTPCacheMaxSize

func (p EngineParams) HTTPCacheMaxSize() int64

func (EngineParams) HTTPCacheMode

func (p EngineParams) HTTPCacheMode() EngineParamsHTTPCacheMode

func (EngineParams) NetworkThreadPriority

func (p EngineParams) NetworkThreadPriority() float64

func (EngineParams) PublicKeyPinsAt

func (p EngineParams) PublicKeyPinsAt(index int) PublicKeyPins

func (EngineParams) PublicKeyPinsSize

func (p EngineParams) PublicKeyPinsSize() int

func (EngineParams) QuicHintAt

func (p EngineParams) QuicHintAt(index int) QuicHint

func (EngineParams) QuicHintSize

func (p EngineParams) QuicHintSize() int

func (EngineParams) SetAcceptLanguage

func (p EngineParams) SetAcceptLanguage(acceptLanguage string)

SetAcceptLanguage sets a default value for the Accept-Language header value for UrlRequests created by this engine. Explicitly setting the Accept-Language header value for individual UrlRequests will override this value.

func (EngineParams) SetAsyncDNS

func (p EngineParams) SetAsyncDNS(enable bool) error

func (EngineParams) SetCronetProxyURLs

func (p EngineParams) SetCronetProxyURLs(proxyURLs []string) error

SetCronetProxyURLs configures a static proxy chain via Cronet experimental options. Each URL uses normal proxy URL syntax, for example:

http://host:8080 , https://host:443 , quic://host:443 , socks5://127.0.0.1:1080 , socks5h://host:port ,
socks4://host:port , http://user:pass@host:8080 , quic://user:pass@host:443 , direct://

Entries are tried in order (fallback). SOCKS5 URLs may include userinfo for RFC 1929 username/password authentication. The socks5h scheme (curl-style alias) is accepted the same as socks5. Pass an empty slice to clear proxy configuration.

func (EngineParams) SetDNSServerOverride

func (p EngineParams) SetDNSServerOverride(nameservers []string) error

SetDNSServerOverride configures Cronet's built-in DNS client to exclusively use the provided nameserver addresses.

The nameserver entries must be IP literals, in "ip:port" form (IPv6 in "[ip]:port" form). Passing an empty slice disables the override.

func (EngineParams) SetEnableBrotli

func (p EngineParams) SetEnableBrotli(enable bool)

SetEnableBrotli sets whether <a href="https://tools.ietf.org/html/rfc7932">Brotli</a> compression is enabled. If enabled, Brotli will be advertised in Accept-Encoding request headers.

func (EngineParams) SetEnableCheckResult

func (p EngineParams) SetEnableCheckResult(enable bool)

SetEnableCheckResult override strict result checking for all operations that return RESULT. If set to true, then failed result will cause native crash via SIGABRT.

func (EngineParams) SetEnableHTTP2

func (p EngineParams) SetEnableHTTP2(enable bool)

SetEnableHTTP2 sets whether <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> protocol is enabled.

func (EngineParams) SetEnablePublicKeyPinningBypassForLocalTrustAnchors

func (p EngineParams) SetEnablePublicKeyPinningBypassForLocalTrustAnchors(enable bool)

SetEnablePublicKeyPinningBypassForLocalTrustAnchors enables or disables public key pinning bypass for local trust anchors. Disabling the bypass for local trust anchors is highly discouraged since it may prohibit the app from communicating with the pinned hosts. E.g., a user may want to send all traffic through an SSL enabled proxy by changing the device proxy settings and adding the proxy certificate to the list of local trust anchor. Disabling the bypass will most likely prevent the app from sending any traffic to the pinned hosts. For more information see 'How does key pinning interact with local proxies and filters?' at https://www.chromium.org/Home/chromium-security/security-faq

func (EngineParams) SetEnableQuic

func (p EngineParams) SetEnableQuic(enable bool)

SetEnableQuic sets whether <a href="https://www.chromium.org/quic">QUIC</a> protocol is enabled. If QUIC is enabled, then QUIC User Agent Id containing application name and Cronet version is sent to the server.

func (EngineParams) SetExperimentalOption

func (p EngineParams) SetExperimentalOption(key string, value any) error

func (EngineParams) SetExperimentalOptions

func (p EngineParams) SetExperimentalOptions(options string)

SetExperimentalOptions set JSON formatted experimental options to be used in Cronet Engine.

func (EngineParams) SetHTTP2Options

func (p EngineParams) SetHTTP2Options(sessionMaxReceiveWindowSize, initialWindowSize uint64) error

func (EngineParams) SetHTTPCacheMaxSize

func (p EngineParams) SetHTTPCacheMaxSize(maxSize int64)

SetHTTPCacheMaxSize sets Maximum size in bytes used to cache data (advisory and maybe exceeded at times)

func (EngineParams) SetHTTPCacheMode

func (p EngineParams) SetHTTPCacheMode(mode EngineParamsHTTPCacheMode)

SetHTTPCacheMode enables or disables caching of HTTP data and other information like QUIC server information.

func (EngineParams) SetHostResolverRules

func (p EngineParams) SetHostResolverRules(rules string) error

SetHostResolverRules sets rules to override DNS resolution. Format: "MAP hostname ip" or "MAP *.example.com ip" or "EXCLUDE hostname". Multiple rules can be separated by commas: "MAP foo 1.2.3.4, MAP bar 5.6.7.8". See net/dns/mapped_host_resolver.h for full format.

func (EngineParams) SetNetworkThreadPriority

func (p EngineParams) SetNetworkThreadPriority(priority float64)

SetNetworkThreadPriority set optional network thread priority. NAN indicates unset, use default. On Android, corresponds to android.os.Process.setThreadPriority() values. On iOS, corresponds to NSThread::setThreadPriority values. Do not specify for other platforms.

func (EngineParams) SetQUICOptions

func (p EngineParams) SetQUICOptions(connectionOptions string, initialStreamRecvWindowSize, initialSessionRecvWindowSize uint64) error

func (EngineParams) SetSocketPoolOptions

func (p EngineParams) SetSocketPoolOptions(maxPerPool, maxPerProxyChain, maxPerGroup int) error

func (EngineParams) SetStoragePath

func (p EngineParams) SetStoragePath(storagePath string)

SetStoragePath sets directory for HTTP Cache and Prefs Storage. The directory must exist.

func (EngineParams) SetUseDnsHttpsSvcb

func (p EngineParams) SetUseDnsHttpsSvcb(enable bool) error

SetUseDnsHttpsSvcb enables or disables DNS HTTPS SVCB record lookups. When enabled, Chromium will query DNS for HTTPS records (type 65) which can contain ECH (Encrypted Client Hello) configurations and ALPN hints. This is required for ECH support.

func (EngineParams) SetUserAgent

func (p EngineParams) SetUserAgent(userAgent string)

SetUserAgent override of the User-Agent header for all requests. An explicitly set User-Agent header will override a value set using this param.

func (EngineParams) StoragePath

func (p EngineParams) StoragePath() string

func (EngineParams) UserAgent

func (p EngineParams) UserAgent() string

type EngineParamsHTTPCacheMode

type EngineParamsHTTPCacheMode int32

EngineParamsHTTPCacheMode specifies HTTP cache mode.

const (
	// HTTPCacheModeDisabled disables caching for the engine.
	HTTPCacheModeDisabled EngineParamsHTTPCacheMode = 0
	// HTTPCacheModeInMemory enables in-memory caching, including HTTP data.
	HTTPCacheModeInMemory EngineParamsHTTPCacheMode = 1
	// HTTPCacheModeDiskNoHTTP enables on-disk caching, excluding HTTP data.
	HTTPCacheModeDiskNoHTTP EngineParamsHTTPCacheMode = 2
	// HTTPCacheModeDisk enables on-disk caching, including HTTP data.
	HTTPCacheModeDisk EngineParamsHTTPCacheMode = 3
)

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error is the base error passed to URLRequestCallbackHandler.OnFailed().

func NewError

func NewError() Error

func (Error) Destroy

func (e Error) Destroy()

func (Error) ErrorCode

func (e Error) ErrorCode() ErrorCode

ErrorCode return the error code, one of ErrorCode values.

func (Error) InternalErrorCode

func (e Error) InternalErrorCode() int

InternalErrorCode is the cronet internal error code. This may provide more specific error diagnosis than ErrorCode(), but the constant values may change over time. See <a href=https://chromium.googlesource.com/chromium/src/+/main/net/base/net_error_list.h> here</a> for the latest list of values.

func (Error) Message

func (e Error) Message() string

Message explaining the error.

func (Error) QuicDetailedErrorCode

func (e Error) QuicDetailedErrorCode() int

QuicDetailedErrorCode contains detailed <a href="https://www.chromium.org/quic">QUIC</a> error code from <a href="https://cs.chromium.org/search/?q=symbol:%5CbQuicErrorCode%5Cb"> QuicErrorCode</a> when the ErrorCode() code is ErrorCodeErrorQuicProtocolFailed.

func (Error) Retryable

func (e Error) Retryable() bool

Retryable |true| if retrying this request right away might succeed, |false| otherwise. For example, is |true| when ErrorCode() is ErrorCodeErrorNetworkChanged because trying the request might succeed using the new network configuration, but |false| when ErrorCode() is ErrorCodeErrorInternetDisconnected because retrying the request right away will encounter the same failure (instead retrying should be delayed until device regains network connectivity).

func (Error) SetErrorCode

func (e Error) SetErrorCode(code ErrorCode)

func (Error) SetInternalErrorCode

func (e Error) SetInternalErrorCode(code int32)

func (Error) SetMessage

func (e Error) SetMessage(message string)

func (Error) SetQuicDetailedErrorCode

func (e Error) SetQuicDetailedErrorCode(code int32)

func (Error) SetRetryable

func (e Error) SetRetryable(retryable bool)

type ErrorCode

type ErrorCode int

ErrorCode represents the error code returned by cronet.

const (
	// ErrorCodeErrorCallback indicating the error returned by app callback.
	ErrorCodeErrorCallback ErrorCode = 0

	// ErrorCodeErrorHostnameNotResolved indicating the host being sent the request could not be resolved to an IP address.
	ErrorCodeErrorHostnameNotResolved ErrorCode = 1

	// ErrorCodeErrorInternetDisconnected indicating the device was not connected to any network.
	ErrorCodeErrorInternetDisconnected ErrorCode = 2

	// ErrorCodeErrorNetworkChanged indicating that as the request was processed the network configuration changed.
	ErrorCodeErrorNetworkChanged ErrorCode = 3

	// ErrorCodeErrorTimedOut indicating a timeout expired. Timeouts expiring while attempting to connect will
	// be reported as the more specific ErrorCodeErrorConnectionTimedOut.
	ErrorCodeErrorTimedOut ErrorCode = 4

	// ErrorCodeErrorConnectionClosed indicating the connection was closed unexpectedly.
	ErrorCodeErrorConnectionClosed ErrorCode = 5

	// ErrorCodeErrorConnectionTimedOut indicating the connection attempt timed out.
	ErrorCodeErrorConnectionTimedOut ErrorCode = 6

	// ErrorCodeErrorConnectionRefused indicating the connection attempt was refused.
	ErrorCodeErrorConnectionRefused ErrorCode = 7

	// ErrorCodeErrorConnectionReset indicating the connection was unexpectedly reset.
	ErrorCodeErrorConnectionReset ErrorCode = 8

	// ErrorCodeErrorAddressUnreachable indicating the IP address being contacted is unreachable,
	// meaning there is no route to the specified host or network.
	ErrorCodeErrorAddressUnreachable ErrorCode = 9

	// ErrorCodeErrorQuicProtocolFailed indicating an error related to the QUIC protocol.
	// When Error.ErrorCode() is this code, see Error.QuicDetailedErrorCode() for more information.
	ErrorCodeErrorQuicProtocolFailed ErrorCode = 10

	// ErrorCodeErrorOther indicating another type of error was encountered.
	// Error.InternalErrorCode() can be consulted to get a more specific cause.
	ErrorCodeErrorOther ErrorCode = 11
)

type ErrorGo

type ErrorGo struct {
	ErrorCode             ErrorCode
	Message               string
	InternalErrorCode     int
	Retryable             bool
	QuicDetailedErrorCode int
}

func ErrorFromError

func ErrorFromError(error Error) *ErrorGo

func (*ErrorGo) Error

func (e *ErrorGo) Error() string

func (*ErrorGo) Temporary

func (e *ErrorGo) Temporary() bool

func (*ErrorGo) Timeout

func (e *ErrorGo) Timeout() bool

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor is an interface provided by the app to run commands asynchronously.

func NewExecutor

func NewExecutor(executeFunc ExecutorExecuteFunc) Executor

func (Executor) ClientContext

func (e Executor) ClientContext() unsafe.Pointer

func (Executor) Destroy

func (e Executor) Destroy()

func (Executor) Execute

func (e Executor) Execute(command Runnable)

func (Executor) SetClientContext

func (e Executor) SetClientContext(context unsafe.Pointer)

type ExecutorExecuteFunc

type ExecutorExecuteFunc func(executor Executor, command Runnable)

ExecutorExecuteFunc takes ownership of |command| and runs it synchronously or asynchronously. Destroys the |command| after execution, or if executor is shutting down.

type HTTPHeader

type HTTPHeader struct {
	// contains filtered or unexported fields
}

HTTPHeader represents an HTTP header key-value pair.

func NewHTTPHeader

func NewHTTPHeader() HTTPHeader

func (HTTPHeader) Destroy

func (h HTTPHeader) Destroy()

func (HTTPHeader) Name

func (h HTTPHeader) Name() string

func (HTTPHeader) SetName

func (h HTTPHeader) SetName(name string)

SetName sets header name

func (HTTPHeader) SetValue

func (h HTTPHeader) SetValue(value string)

SetValue sts header value

func (HTTPHeader) Value

func (h HTTPHeader) Value() string

type Metrics

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics contains timing metrics for a URLRequest.

func NewMetrics

func NewMetrics() Metrics

func (Metrics) ConnectEnd

func (m Metrics) ConnectEnd() DateTime

ConnectEnd Time when connection establishment finished, after TCP connection is established and, if using HTTPS, SSL handshake is completed. For QUIC 0-RTT, this represents the time of handshake confirmation and might happen later than SendingStart. Will equal null if the socket was reused (see SocketReused).

func (Metrics) ConnectStart

func (m Metrics) ConnectStart() DateTime

ConnectStart Time when connection establishment started, typically when DNS resolution finishes. Will equal null if the socket was reused (see SocketReused).

func (Metrics) DNSEnd

func (m Metrics) DNSEnd() DateTime

DNSEnd Time when DNS lookup finished. This and DNSStart will return non-null regardless of whether the result came from a DNS server or the local cache. Will equal null if the socket was reused (see SocketReused).

func (Metrics) DNSStart

func (m Metrics) DNSStart() DateTime

DNSStart Time when DNS lookup started. This and DNSEnd will be set to non-null regardless of whether the result came from a DNS server or the local cache. Will equal null if the socket was reused (see SocketReused).

func (Metrics) Destroy

func (m Metrics) Destroy()

func (Metrics) PushEnd

func (m Metrics) PushEnd() DateTime

PushEnd Time when last byte of HTTP/2 server push was received. Will equal null if server push is not used.

func (Metrics) PushStart

func (m Metrics) PushStart() DateTime

PushStart Time when first byte of HTTP/2 server push was received. Will equal null if server push is not used.

func (Metrics) ReceivedByteCount

func (m Metrics) ReceivedByteCount() int64

ReceivedByteCount Total bytes received over the network transport layer, or -1 if not collected. Number of bytes does not include any previous redirects.

func (Metrics) RequestStart

func (m Metrics) RequestStart() DateTime

RequestStart Time when the request started, which corresponds to calling Cronet_UrlRequest_Start(). This timestamp will match the system clock at the time it represents.

func (Metrics) ResponseEnd

func (m Metrics) ResponseEnd() DateTime

ResponseEnd Time when the request finished.

func (Metrics) ResponseStart

func (m Metrics) ResponseStart() DateTime

ResponseStart Time when the end of the response headers was received.

Will equal null if the request failed or was canceled before the response started.

func (Metrics) SSLEnd

func (m Metrics) SSLEnd() DateTime

SSLEnd Time when SSL handshake finished. For QUIC, this will be the same time as ConnectEnd. Will equal null if SSL is not used or if the socket was reused (see SocketReused).

func (Metrics) SSLStart

func (m Metrics) SSLStart() DateTime

SSLStart Time when SSL handshake started. For QUIC, this will be the same time as ConnectStart. Will equal null if SSL is not used or if the socket was reused (see SocketReused).

func (Metrics) SendingEnd

func (m Metrics) SendingEnd() DateTime

SendingEnd Time when sending HTTP request body finished. (Sending request body happens after sending request headers.)

Will equal null if the request failed or was canceled before sending ended.

func (Metrics) SendingStart

func (m Metrics) SendingStart() DateTime

SendingStart Time when sending HTTP request headers started.

Will equal null if the request failed or was canceled before sending started.

func (Metrics) SentByteCount

func (m Metrics) SentByteCount() int64

SentByteCount Returns total bytes sent over the network transport layer, or -1 if not collected.

func (Metrics) SetConnectEnd

func (m Metrics) SetConnectEnd(t DateTime)

func (Metrics) SetConnectStart

func (m Metrics) SetConnectStart(t DateTime)

func (Metrics) SetDNSEnd

func (m Metrics) SetDNSEnd(t DateTime)

func (Metrics) SetDNSStart

func (m Metrics) SetDNSStart(t DateTime)

func (Metrics) SetPushEnd

func (m Metrics) SetPushEnd(t DateTime)

func (Metrics) SetPushStart

func (m Metrics) SetPushStart(t DateTime)

func (Metrics) SetReceivedByteCount

func (m Metrics) SetReceivedByteCount(count int64)

func (Metrics) SetRequestEnd

func (m Metrics) SetRequestEnd(t DateTime)

func (Metrics) SetRequestStart

func (m Metrics) SetRequestStart(t DateTime)

func (Metrics) SetResponseStart

func (m Metrics) SetResponseStart(t DateTime)

func (Metrics) SetSSLEnd

func (m Metrics) SetSSLEnd(t DateTime)

func (Metrics) SetSSLStart

func (m Metrics) SetSSLStart(t DateTime)

func (Metrics) SetSendingEnd

func (m Metrics) SetSendingEnd(t DateTime)

func (Metrics) SetSendingStart

func (m Metrics) SetSendingStart(t DateTime)

func (Metrics) SetSentByteCount

func (m Metrics) SetSentByteCount(count int64)

func (Metrics) SetSocketReused

func (m Metrics) SetSocketReused(reused bool)

func (Metrics) SocketReused

func (m Metrics) SocketReused() bool

SocketReused True if the socket was reused from a previous request, false otherwise. In HTTP/2 or QUIC, if streams are multiplexed in a single connection, this will be {@code true} for all streams after the first. When {@code true}, DNS, connection, and SSL times will be null.

type NaiveClient

type NaiveClient struct {
	// contains filtered or unexported fields
}

func NewNaiveClient

func NewNaiveClient(config NaiveClientOptions) (*NaiveClient, error)

func (*NaiveClient) Close

func (c *NaiveClient) Close() error

func (*NaiveClient) DialContext

func (c *NaiveClient) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error)

func (*NaiveClient) DialEarly

func (c *NaiveClient) DialEarly(ctx context.Context, destination M.Socksaddr) (NaiveConn, error)

func (*NaiveClient) Engine

func (c *NaiveClient) Engine() Engine

func (*NaiveClient) ListenPacket

func (c *NaiveClient) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error)

func (*NaiveClient) Start

func (c *NaiveClient) Start() error

type NaiveClientOptions

type NaiveClientOptions struct {
	Context                  context.Context
	ServerAddress            M.Socksaddr
	ServerName               string
	Username                 string
	Password                 string
	InsecureConcurrency      int
	ReceiveWindow            uint64
	ExtraHeaders             map[string]string
	TrustedRootCertificates  string
	DNSResolver              DNSResolverFunc
	Logger                   logger.ContextLogger
	Dialer                   N.Dialer
	ECHEnabled               bool
	ECHConfigList            []byte
	ECHQueryServerName       string
	TestForceUDPLoopback     bool
	QUIC                     bool
	QUICCongestionControl    QUICCongestionControl
	QUICSessionReceiveWindow uint64
}

type NaiveConn

type NaiveConn interface {
	net.Conn
	Handshake() error
	HandshakeContext(ctx context.Context) error
}

type NetError

type NetError int

NetError represents a Chromium network error code. Error codes are negative integers defined in Chromium's net/base/net_error_list.h.

const (
	NetErrorIOPending                                             NetError = -1
	NetErrorFailed                                                NetError = -2
	NetErrorAborted                                               NetError = -3
	NetErrorInvalidArgument                                       NetError = -4
	NetErrorInvalidHandle                                         NetError = -5
	NetErrorFileNotFound                                          NetError = -6
	NetErrorTimedOut                                              NetError = -7
	NetErrorFileTooBig                                            NetError = -8
	NetErrorUnexpected                                            NetError = -9
	NetErrorAccessDenied                                          NetError = -10
	NetErrorNotImplemented                                        NetError = -11
	NetErrorInsufficientResources                                 NetError = -12
	NetErrorOutOfMemory                                           NetError = -13
	NetErrorUploadFileChanged                                     NetError = -14
	NetErrorSocketNotConnected                                    NetError = -15
	NetErrorFileExists                                            NetError = -16
	NetErrorFilePathTooLong                                       NetError = -17
	NetErrorFileNoSpace                                           NetError = -18
	NetErrorFileVirusInfected                                     NetError = -19
	NetErrorBlockedByClient                                       NetError = -20
	NetErrorNetworkChanged                                        NetError = -21
	NetErrorBlockedByAdministrator                                NetError = -22
	NetErrorSocketIsConnected                                     NetError = -23
	NetErrorUploadStreamRewindNotSupported                        NetError = -25
	NetErrorContextShutDown                                       NetError = -26
	NetErrorBlockedByResponse                                     NetError = -27
	NetErrorCleartextNotPermitted                                 NetError = -29
	NetErrorBlockedByCSP                                          NetError = -30
	NetErrorBlockedByORB                                          NetError = -32
	NetErrorNetworkAccessRevoked                                  NetError = -33
	NetErrorBlockedByFingerprintingProtection                     NetError = -34
	NetErrorConnectionClosed                                      NetError = -100
	NetErrorConnectionReset                                       NetError = -101
	NetErrorConnectionRefused                                     NetError = -102
	NetErrorConnectionAborted                                     NetError = -103
	NetErrorConnectionFailed                                      NetError = -104
	NetErrorNameNotResolved                                       NetError = -105
	NetErrorInternetDisconnected                                  NetError = -106
	NetErrorSSLProtocolError                                      NetError = -107
	NetErrorAddressInvalid                                        NetError = -108
	NetErrorAddressUnreachable                                    NetError = -109
	NetErrorSSLClientAuthCertNeeded                               NetError = -110
	NetErrorTunnelConnectionFailed                                NetError = -111
	NetErrorNoSSLVersionsEnabled                                  NetError = -112
	NetErrorSSLVersionOrCipherMismatch                            NetError = -113
	NetErrorSSLRenegotiationRequested                             NetError = -114
	NetErrorProxyAuthUnsupported                                  NetError = -115
	NetErrorBadSSLClientAuthCert                                  NetError = -117
	NetErrorConnectionTimedOut                                    NetError = -118
	NetErrorHostResolverQueueTooLarge                             NetError = -119
	NetErrorSOCKSConnectionFailed                                 NetError = -120
	NetErrorSOCKSConnectionHostUnreachable                        NetError = -121
	NetErrorAlpnNegotiationFailed                                 NetError = -122
	NetErrorSSLNoRenegotiation                                    NetError = -123
	NetErrorWinsockUnexpectedWrittenBytes                         NetError = -124
	NetErrorSSLDecompressionFailureAlert                          NetError = -125
	NetErrorSSLBadRecordMACAlert                                  NetError = -126
	NetErrorProxyAuthRequested                                    NetError = -127
	NetErrorProxyConnectionFailed                                 NetError = -130
	NetErrorMandatoryProxyConfigurationFailed                     NetError = -131
	NetErrorPreconnectMaxSocketLimit                              NetError = -133
	NetErrorSSLClientAuthPrivateKeyAccessDenied                   NetError = -134
	NetErrorSSLClientAuthCertNoPrivateKey                         NetError = -135
	NetErrorProxyCertificateInvalid                               NetError = -136
	NetErrorNameResolutionFailed                                  NetError = -137
	NetErrorNetworkAccessDenied                                   NetError = -138
	NetErrorTemporarilyThrottled                                  NetError = -139
	NetErrorHttpsProxyTunnelResponseRedirect                      NetError = -140
	NetErrorSSLClientAuthSignatureFailed                          NetError = -141
	NetErrorMsgTooBig                                             NetError = -142
	NetErrorWsProtocolError                                       NetError = -145
	NetErrorAddressInUse                                          NetError = -147
	NetErrorSSLHandshakeNotCompleted                              NetError = -148
	NetErrorSSLBadPeerPublicKey                                   NetError = -149
	NetErrorSSLPinnedKeyNotInCertChain                            NetError = -150
	NetErrorClientAuthCertTypeUnsupported                         NetError = -151
	NetErrorSSLDecryptErrorAlert                                  NetError = -153
	NetErrorWsThrottleQueueTooLarge                               NetError = -154
	NetErrorSSLServerCertChanged                                  NetError = -156
	NetErrorSSLUnrecognizedNameAlert                              NetError = -159
	NetErrorSocketSetReceiveBufferSizeError                       NetError = -160
	NetErrorSocketSetSendBufferSizeError                          NetError = -161
	NetErrorSocketReceiveBufferSizeUnchangeable                   NetError = -162
	NetErrorSocketSendBufferSizeUnchangeable                      NetError = -163
	NetErrorSSLClientAuthCertBadFormat                            NetError = -164
	NetErrorIcannNameCollision                                    NetError = -166
	NetErrorSSLServerCertBadFormat                                NetError = -167
	NetErrorCTSthParsingFailed                                    NetError = -168
	NetErrorCTSthIncomplete                                       NetError = -169
	NetErrorUnableToReuseConnectionForProxyAuth                   NetError = -170
	NetErrorCTConsistencyProofParsingFailed                       NetError = -171
	NetErrorSSLObsoleteCipher                                     NetError = -172
	NetErrorWsUpgrade                                             NetError = -173
	NetErrorReadIfReadyNotImplemented                             NetError = -174
	NetErrorNoBufferSpace                                         NetError = -176
	NetErrorSSLClientAuthNoCommonAlgorithms                       NetError = -177
	NetErrorEarlyDataRejected                                     NetError = -178
	NetErrorWrongVersionOnEarlyData                               NetError = -179
	NetErrorTls13DowngradeDetected                                NetError = -180
	NetErrorSSLKeyUsageIncompatible                               NetError = -181
	NetErrorInvalidECHConfigList                                  NetError = -182
	NetErrorECHNotNegotiated                                      NetError = -183
	NetErrorECHFallbackCertificateInvalid                         NetError = -184
	NetErrorProxyUnableToConnectToDestination                     NetError = -186
	NetErrorProxyDelegateCanceledConnectRequest                   NetError = -187
	NetErrorProxyDelegateCanceledConnectResponse                  NetError = -188
	NetErrorCertCommonNameInvalid                                 NetError = -200
	NetErrorCertDateInvalid                                       NetError = -201
	NetErrorCertAuthorityInvalid                                  NetError = -202
	NetErrorCertContainsErrors                                    NetError = -203
	NetErrorCertNoRevocationMechanism                             NetError = -204
	NetErrorCertUnableToCheckRevocation                           NetError = -205
	NetErrorCertRevoked                                           NetError = -206
	NetErrorCertInvalid                                           NetError = -207
	NetErrorCertWeakSignatureAlgorithm                            NetError = -208
	NetErrorCertNonUniqueName                                     NetError = -210
	NetErrorCertWeakKey                                           NetError = -211
	NetErrorCertNameConstraintViolation                           NetError = -212
	NetErrorCertValidityTooLong                                   NetError = -213
	NetErrorCertificateTransparencyRequired                       NetError = -214
	NetErrorCertKnownInterceptionBlocked                          NetError = -217
	NetErrorCertSelfSignedLocalNetwork                            NetError = -219
	NetErrorInvalidURL                                            NetError = -300
	NetErrorDisallowedURLScheme                                   NetError = -301
	NetErrorUnknownURLScheme                                      NetError = -302
	NetErrorInvalidRedirect                                       NetError = -303
	NetErrorTooManyRedirects                                      NetError = -310
	NetErrorUnsafeRedirect                                        NetError = -311
	NetErrorUnsafePort                                            NetError = -312
	NetErrorInvalidResponse                                       NetError = -320
	NetErrorInvalidChunkedEncoding                                NetError = -321
	NetErrorMethodNotSupported                                    NetError = -322
	NetErrorUnexpectedProxyAuth                                   NetError = -323
	NetErrorEmptyResponse                                         NetError = -324
	NetErrorResponseHeadersTooBig                                 NetError = -325
	NetErrorPACScriptFailed                                       NetError = -327
	NetErrorRequestRangeNotSatisfiable                            NetError = -328
	NetErrorMalformedIdentity                                     NetError = -329
	NetErrorContentDecodingFailed                                 NetError = -330
	NetErrorNetworkIOSuspended                                    NetError = -331
	NetErrorSynReplyNotReceived                                   NetError = -332
	NetErrorEncodingConversionFailed                              NetError = -333
	NetErrorUnrecognizedFtpDirectoryListingFormat                 NetError = -334
	NetErrorNoSupportedProxies                                    NetError = -336
	NetErrorHTTP2ProtocolError                                    NetError = -337
	NetErrorInvalidAuthCredentials                                NetError = -338
	NetErrorUnsupportedAuthScheme                                 NetError = -339
	NetErrorEncodingDetectionFailed                               NetError = -340
	NetErrorMissingAuthCredentials                                NetError = -341
	NetErrorUnexpectedSecurityLibraryStatus                       NetError = -342
	NetErrorMisconfiguredAuthEnvironment                          NetError = -343
	NetErrorUndocumentedSecurityLibraryStatus                     NetError = -344
	NetErrorResponseBodyTooBigToDrain                             NetError = -345
	NetErrorResponseHeadersMultipleContentLength                  NetError = -346
	NetErrorIncompleteHTTP2Headers                                NetError = -347
	NetErrorPACNotInDhcp                                          NetError = -348
	NetErrorResponseHeadersMultipleContentDisposition             NetError = -349
	NetErrorResponseHeadersMultipleLocation                       NetError = -350
	NetErrorHTTP2ServerRefusedStream                              NetError = -351
	NetErrorHTTP2PingFailed                                       NetError = -352
	NetErrorContentLengthMismatch                                 NetError = -354
	NetErrorIncompleteChunkedEncoding                             NetError = -355
	NetErrorQUICProtocolError                                     NetError = -356
	NetErrorResponseHeadersTruncated                              NetError = -357
	NetErrorQUICHandshakeFailed                                   NetError = -358
	NetErrorHTTP2InadequateTransportSecurity                      NetError = -360
	NetErrorHTTP2FlowControlError                                 NetError = -361
	NetErrorHTTP2FrameSizeError                                   NetError = -362
	NetErrorHTTP2CompressionError                                 NetError = -363
	NetErrorProxyAuthRequestedWithNoConnection                    NetError = -364
	NetErrorHTTP11Required                                        NetError = -365
	NetErrorProxyHTTP11Required                                   NetError = -366
	NetErrorPACScriptTerminated                                   NetError = -367
	NetErrorProxyRequired                                         NetError = -368
	NetErrorInvalidHTTPResponse                                   NetError = -370
	NetErrorContentDecodingInitFailed                             NetError = -371
	NetErrorHTTP2RSTStreamNoErrorReceived                         NetError = -372
	NetErrorTooManyRetries                                        NetError = -375
	NetErrorHTTP2StreamClosed                                     NetError = -376
	NetErrorHTTPResponseCodeFailure                               NetError = -379
	NetErrorQUICCertRootNotKnown                                  NetError = -380
	NetErrorQUICGoawayRequestCanBeRetried                         NetError = -381
	NetErrorTooManyAcceptChRestarts                               NetError = -382
	NetErrorInconsistentIPAddressSpace                            NetError = -383
	NetErrorCachedIPAddressSpaceBlockedByLocalNetworkAccessPolicy NetError = -384
	NetErrorBlockedByLocalNetworkAccessChecks                     NetError = -385
	NetErrorZstdWindowSizeTooBig                                  NetError = -386
	NetErrorDictionaryLoadFailed                                  NetError = -387
	NetErrorUnexpectedContentDictionaryHeader                     NetError = -388
	NetErrorCacheMiss                                             NetError = -400
	NetErrorCacheReadFailure                                      NetError = -401
	NetErrorCacheWriteFailure                                     NetError = -402
	NetErrorCacheOperationNotSupported                            NetError = -403
	NetErrorCacheOpenFailure                                      NetError = -404
	NetErrorCacheCreateFailure                                    NetError = -405
	NetErrorCacheRace                                             NetError = -406
	NetErrorCacheChecksumReadFailure                              NetError = -407
	NetErrorCacheChecksumMismatch                                 NetError = -408
	NetErrorCacheLockTimeout                                      NetError = -409
	NetErrorCacheAuthFailureAfterRead                             NetError = -410
	NetErrorCacheEntryNotSuitable                                 NetError = -411
	NetErrorCacheDoomFailure                                      NetError = -412
	NetErrorCacheOpenOrCreateFailure                              NetError = -413
	NetErrorInsecureResponse                                      NetError = -501
	NetErrorNoPrivateKeyForCert                                   NetError = -502
	NetErrorAddUserCertFailed                                     NetError = -503
	NetErrorInvalidSignedExchange                                 NetError = -504
	NetErrorInvalidWebBundle                                      NetError = -505
	NetErrorTrustTokenOperationFailed                             NetError = -506
	NetErrorTrustTokenOperationSuccessWithoutSendingRequest       NetError = -507
	NetErrorPkcs12ImportBadPassword                               NetError = -701
	NetErrorPkcs12ImportFailed                                    NetError = -702
	NetErrorImportCaCertNotCa                                     NetError = -703
	NetErrorImportCertAlreadyExists                               NetError = -704
	NetErrorImportCaCertFailed                                    NetError = -705
	NetErrorImportServerCertFailed                                NetError = -706
	NetErrorPkcs12ImportInvalidMAC                                NetError = -707
	NetErrorPkcs12ImportInvalidFile                               NetError = -708
	NetErrorPkcs12ImportUnsupported                               NetError = -709
	NetErrorKeyGenerationFailed                                   NetError = -710
	NetErrorPrivateKeyExportFailed                                NetError = -712
	NetErrorSelfSignedCertGenerationFailed                        NetError = -713
	NetErrorCertDatabaseChanged                                   NetError = -714
	NetErrorCertVerifierChanged                                   NetError = -716
	NetErrorDNSMalformedResponse                                  NetError = -800
	NetErrorDNSServerRequiresTCP                                  NetError = -801
	NetErrorDNSServerFailed                                       NetError = -802
	NetErrorDNSTimedOut                                           NetError = -803
	NetErrorDNSCacheMiss                                          NetError = -804
	NetErrorDNSSearchEmpty                                        NetError = -805
	NetErrorDNSSortError                                          NetError = -806
	NetErrorDNSSecureResolverHostnameResolutionFailed             NetError = -808
	NetErrorDNSNameHttpsOnly                                      NetError = -809
	NetErrorDNSRequestCancelled                                   NetError = -810
	NetErrorDNSNoMatchingSupportedAlpn                            NetError = -811
	NetErrorDNSSecureProbeRecordInvalid                           NetError = -814
	NetErrorDNSCacheInvalidationInProgress                        NetError = -815
	NetErrorBlobInvalidConstructionArguments                      NetError = -900
	NetErrorBlobOutOfMemory                                       NetError = -901
	NetErrorBlobFileWriteFailed                                   NetError = -902
	NetErrorBlobSourceDiedInTransit                               NetError = -903
	NetErrorBlobDereferencedWhileBuilding                         NetError = -904
	NetErrorBlobReferencedBlobBroken                              NetError = -905
	NetErrorBlobReferencedFileUnavailable                         NetError = -906
)

NetError constants from Chromium's net_error_list.h

func (NetError) Code

func (e NetError) Code() int

Code returns the raw error code as an integer.

func (NetError) Description

func (e NetError) Description() string

Description returns the full description from Chromium source.

func (NetError) Error

func (e NetError) Error() string

Error implements the error interface with a Go-style lowercase message.

func (NetError) Is

func (e NetError) Is(target error) bool

Is implements errors.Is() support for comparing NetError with Go standard errors.

func (NetError) Name

func (e NetError) Name() string

Name returns the Chromium error name (e.g., "ERR_CONNECTION_REFUSED").

func (NetError) Temporary

func (e NetError) Temporary() bool

Temporary returns false. Chromium errors are not considered temporary. This implements the net.Error interface.

func (NetError) Timeout

func (e NetError) Timeout() bool

Timeout returns true if this error represents a timeout. This implements the net.Error interface.

type PublicKeyPins

type PublicKeyPins struct {
	// contains filtered or unexported fields
}

PublicKeyPins contains public key pins for certificate validation.

func NewPublicKeyPins

func NewPublicKeyPins() PublicKeyPins

func (PublicKeyPins) AddPinnedSHA256

func (p PublicKeyPins) AddPinnedSHA256(hash string)

AddPinnedSHA256 add pins. each pin is the SHA-256 cryptographic hash (in the form of "sha256/<base64-hash-value>") of the DER-encoded ASN.1 representation of the Subject Public Key Info (SPKI) of the host's X.509 certificate. Although, the method does not mandate the presence of the backup pin that can be used if the control of the primary private key has been lost, it is highly recommended to supply one.

func (PublicKeyPins) ClearPinnedSHA256

func (p PublicKeyPins) ClearPinnedSHA256()

func (PublicKeyPins) Destroy

func (p PublicKeyPins) Destroy()

func (PublicKeyPins) ExpirationDate

func (p PublicKeyPins) ExpirationDate() int64

func (PublicKeyPins) Host

func (p PublicKeyPins) Host() string

func (PublicKeyPins) IncludeSubdomains

func (p PublicKeyPins) IncludeSubdomains() bool

func (PublicKeyPins) PinnedSHA256At

func (p PublicKeyPins) PinnedSHA256At(index int) string

func (PublicKeyPins) PinnedSHA256Size

func (p PublicKeyPins) PinnedSHA256Size() int

func (PublicKeyPins) SetExpirationDate

func (p PublicKeyPins) SetExpirationDate(date int64)

SetExpirationDate set the expiration date for the pins in milliseconds since epoch (as in java.util.Date).

func (PublicKeyPins) SetHost

func (p PublicKeyPins) SetHost(host string)

SetHost set name of the host to which the public keys should be pinned. A host that consists only of digits and the dot character is treated as invalid.

func (PublicKeyPins) SetIncludeSubdomains

func (p PublicKeyPins) SetIncludeSubdomains(includeSubdomains bool)

SetIncludeSubdomains set whether the pinning policy should be applied to subdomains of |host|.

type QUICCongestionControl

type QUICCongestionControl string
const (
	QUICCongestionControlDefault QUICCongestionControl = ""
	QUICCongestionControlBBR     QUICCongestionControl = "TBBR"
	QUICCongestionControlBBRv2   QUICCongestionControl = "B2ON"
	QUICCongestionControlCubic   QUICCongestionControl = "QBIC"
	QUICCongestionControlReno    QUICCongestionControl = "RENO"
)

type QuicHint

type QuicHint struct {
	// contains filtered or unexported fields
}

QuicHint contains hints for QUIC protocol usage.

func NewQuicHint

func NewQuicHint() QuicHint

func (QuicHint) AlternatePort

func (h QuicHint) AlternatePort() int32

func (QuicHint) Destroy

func (h QuicHint) Destroy()

func (QuicHint) Host

func (h QuicHint) Host() string

func (QuicHint) Port

func (h QuicHint) Port() int32

func (QuicHint) SetAlternatePort

func (h QuicHint) SetAlternatePort(port int32)

SetAlternatePort set alternate port to use for QUIC

func (QuicHint) SetHost

func (h QuicHint) SetHost(host string)

SetHost set name of the host that supports QUIC.

func (QuicHint) SetPort

func (h QuicHint) SetPort(port int32)

SetPort set port of the server that supports QUIC.

type RequestFinishedInfo

type RequestFinishedInfo struct {
	// contains filtered or unexported fields
}

RequestFinishedInfo contains information about a finished request.

func NewURLRequestFinishedInfo

func NewURLRequestFinishedInfo() RequestFinishedInfo

func (RequestFinishedInfo) AddAnnotation

func (i RequestFinishedInfo) AddAnnotation(annotation unsafe.Pointer)

func (RequestFinishedInfo) AnnotationAt

func (i RequestFinishedInfo) AnnotationAt(index int) unsafe.Pointer

func (RequestFinishedInfo) AnnotationSize

func (i RequestFinishedInfo) AnnotationSize() int

AnnotationSize The objects that the caller has supplied when initiating the request, using URLRequestParams.AddAnnotation

Annotations can be used to associate a RequestFinishedInfo with the original request or type of request.

func (RequestFinishedInfo) ClearAnnotations

func (i RequestFinishedInfo) ClearAnnotations()

func (RequestFinishedInfo) Destroy

func (i RequestFinishedInfo) Destroy()

func (RequestFinishedInfo) FinishedReason

FinishedReason Returns the reason why the request finished.

func (RequestFinishedInfo) Metrics

func (i RequestFinishedInfo) Metrics() Metrics

Metrics Metrics collected for this request.

func (RequestFinishedInfo) SetFinishedReason

func (i RequestFinishedInfo) SetFinishedReason(reason URLRequestFinishedInfoFinishedReason)

func (RequestFinishedInfo) SetMetrics

func (i RequestFinishedInfo) SetMetrics(metrics Metrics)

type Result

type Result int

Result is runtime result code returned by Engine and URLRequest. Equivalent to runtime exceptions in Android Java API. All results except SUCCESS trigger native crash (via SIGABRT triggered by CHECK failure) unless EngineParams.EnableCheckResult is set to false.

const (
	// ResultSuccess Operation completed successfully
	ResultSuccess Result = 0

	// ResultIllegalArgument Illegal argument
	ResultIllegalArgument Result = -100

	// ResultIllegalArgumentStoragePathMustExist Storage path must be set to existing directory
	ResultIllegalArgumentStoragePathMustExist Result = -101

	// ResultIllegalArgumentInvalidPin Public key pin is invalid
	ResultIllegalArgumentInvalidPin Result = -102

	// ResultIllegalArgumentInvalidHostname Host name is invalid
	ResultIllegalArgumentInvalidHostname Result = -103

	// ResultIllegalArgumentInvalidHttpMethod Invalid http method
	ResultIllegalArgumentInvalidHttpMethod Result = -104

	// ResultIllegalArgumentInvalidHttpHeader Invalid http header
	ResultIllegalArgumentInvalidHttpHeader Result = -105

	// ResultIllegalState Illegal state
	ResultIllegalState Result = -200

	// ResultIllegalStateStoragePathInUse Storage path is used by another engine
	ResultIllegalStateStoragePathInUse Result = -201

	// ResultIllegalStateCannotShutdownEngineFromNetworkThread Cannot shutdown engine from network thread
	ResultIllegalStateCannotShutdownEngineFromNetworkThread Result = -202

	// ResultIllegalStateEngineAlreadyStarted The engine has already started
	ResultIllegalStateEngineAlreadyStarted Result = -203

	// ResultIllegalStateRequestAlreadyStarted The request has already started
	ResultIllegalStateRequestAlreadyStarted Result = -204

	// ResultIllegalStateRequestNotInitialized The request is not initialized
	ResultIllegalStateRequestNotInitialized Result = -205

	// ResultIllegalStateRequestAlreadyInitialized The request is already initialized
	ResultIllegalStateRequestAlreadyInitialized Result = -206

	// ResultIllegalStateRequestNotStarted The request is not started
	ResultIllegalStateRequestNotStarted Result = -207

	// ResultIllegalStateUnexpectedRedirect No redirect to follow
	ResultIllegalStateUnexpectedRedirect Result = -208

	// ResultIllegalStateUnexpectedRead Unexpected read attempt
	ResultIllegalStateUnexpectedRead Result = -209

	// ResultIllegalStateReadFailed Unexpected read failure
	ResultIllegalStateReadFailed Result = -210

	// ResultNullPointer Null pointer or empty data
	ResultNullPointer Result = -300

	// ResultNullPointerHostname The hostname cannot be null
	ResultNullPointerHostname Result = -301

	// ResultNullPointerSha256Pins The set of SHA256 pins cannot be null
	ResultNullPointerSha256Pins Result = -302

	// ResultNullPointerExpirationDate The pin expiration date cannot be null
	ResultNullPointerExpirationDate Result = -303

	// ResultNullPointerEngine Engine is required
	ResultNullPointerEngine Result = -304

	// ResultNullPointerURL URL is required
	ResultNullPointerURL Result = -305

	// ResultNullPointerCallback Callback is required
	ResultNullPointerCallback Result = -306

	// ResultNullPointerExecutor Executor is required
	ResultNullPointerExecutor Result = -307

	// ResultNullPointerMethod Method is required
	ResultNullPointerMethod Result = -308

	// ResultNullPointerHeaderName Invalid header name
	ResultNullPointerHeaderName Result = -309

	// ResultNullPointerHeaderValue Invalid header value
	ResultNullPointerHeaderValue Result = -310

	// ResultNullPointerParams Params is required
	ResultNullPointerParams Result = -311

	// ResultNullPointerRequestFinishedInfoListenerExecutor Executor for RequestFinishedInfoListener is required
	ResultNullPointerRequestFinishedInfoListenerExecutor Result = -312
)

type RoundTripper

type RoundTripper struct {
	CheckRedirect func(newLocationUrl string) bool
	Engine        Engine

	// ProxyFunc, if non-nil, is called when the RoundTripper creates its own Engine
	// (Engine is zero on first use). Returned URLs are passed to SetCronetProxyURLs
	// before StartWithParams. Same semantics as SetCronetProxyURLs: ordered fallback list.
	// Ignored when Engine is set explicitly by the caller.
	ProxyFunc func() ([]string, error)

	// TrustedRootPEM, if non-empty, is one or more PEM-encoded certificates
	// (concatenated) that are trusted as root CAs when the RoundTripper creates
	// its own Engine (Engine is zero on first use). Multiple certificates can be
	// included in a single string by concatenating their PEM blocks. Applied
	// before StartWithParams.
	// InsecureSkipVerify and TrustedRootPEM must not both be set.
	TrustedRootPEM string

	// InsecureSkipVerify disables TLS certificate verification entirely (testing only).
	// InsecureSkipVerify and TrustedRootPEM must not both be set.
	InsecureSkipVerify bool
	// contains filtered or unexported fields
}

RoundTripper is a wrapper from URLRequest to http.RoundTripper

func (*RoundTripper) Close

func (t *RoundTripper) Close()

Close shuts down any Engine that the RoundTripper created internally (i.e. one not supplied by the caller). It is safe to call Close concurrently with RoundTrip. After Close returns, subsequent RoundTrip calls return net.ErrClosed immediately. Close is idempotent.

func (*RoundTripper) RoundTrip

func (t *RoundTripper) RoundTrip(request *http.Request) (*http.Response, error)

type Runnable

type Runnable struct {
	// contains filtered or unexported fields
}

Runnable is a command to be executed by an Executor.

func NewRunnable

func NewRunnable(runFunc RunnableRunFunc) Runnable

NewRunnable creates a new Runnable with the given run function.

func (Runnable) ClientContext

func (r Runnable) ClientContext() unsafe.Pointer

func (Runnable) Destroy

func (r Runnable) Destroy()

func (Runnable) Run

func (r Runnable) Run()

func (Runnable) SetClientContext

func (r Runnable) SetClientContext(context unsafe.Pointer)

type RunnableRunFunc

type RunnableRunFunc func(self Runnable)

RunnableRunFunc is the function type for Runnable.Run callback.

type StreamEngine

type StreamEngine struct {
	// contains filtered or unexported fields
}

StreamEngine is an opaque object representing a Bidirectional stream creating engine. Created and configured outside of this API to facilitate sharing with other components.

func (StreamEngine) CreateConn

func (e StreamEngine) CreateConn(ctx context.Context, l logger.ContextLogger, readWaitHeaders bool, writeWaitHeaders bool) *BidirectionalConn

func (StreamEngine) CreateStream

CreateStream Creates a new stream object that uses |engine| and |callback|. All stream tasks are performed asynchronously on the |engine| network thread. |callback| methods are invoked synchronously on the |engine| network thread, but must not run tasks on the current thread to prevent blocking networking operations and causing exceptions during shutdown. The |annotation| is stored in bidirectional stream for arbitrary use by application.

Returned |bidirectional_stream*| is owned by the caller, and must be destroyed using |bidirectional_stream_destroy|.

Both |calback| and |engine| must remain valid until stream is destroyed.

type UDPDialer

type UDPDialer func(address string, port uint16) (fd int, localAddress string, localPort uint16)

UDPDialer is a callback function for custom UDP socket creation. address: IP address string (e.g. "1.2.3.4" or "::1") port: Port number Returns:

  • fd: socket fd on success, negative net error code on failure
  • localAddress: local IP address string (may be empty)
  • localPort: local port number

The returned socket can be:

  • AF_INET/AF_INET6 SOCK_DGRAM: Standard UDP socket (may be connected)
  • AF_UNIX SOCK_DGRAM: Unix domain datagram socket (Unix/macOS/Linux)
  • AF_UNIX SOCK_STREAM: Unix domain stream socket (Windows, with framing)

Cronet will NOT call connect() on the returned socket.

type URLRequest

type URLRequest struct {
	// contains filtered or unexported fields
}

URLRequest controls an HTTP request (GET, PUT, POST etc). Initialized by InitWithParams(). Note: All methods must be called on the Executor passed to InitWithParams().

func NewURLRequest

func NewURLRequest() URLRequest

func NewURLRequestWith

func NewURLRequestWith(handler URLRequestHandler) URLRequest

NewURLRequestWith creates a new URLRequest with custom handler (for testing/mocking).

func (URLRequest) Cancel

func (r URLRequest) Cancel()

Cancel cancels the request. Can be called at any time. URLRequestCallbackHandler.OnCanceled() will be invoked when cancellation is complete and no further callback methods will be invoked. If the request has completed or has not started, calling Cancel() has no effect and URLRequestCallbackHandler.OnCanceled() will not be invoked. If the Executor passed in to UrlRequest.InitWithParams() runs tasks on a single thread, and Cancel() is called on that thread, no callback methods (besides URLRequestCallbackHandler.OnCanceled() will be invoked after Cancel() is called. Otherwise, at most one callback method may be invoked after Cancel() has completed.

func (URLRequest) ClientContext

func (r URLRequest) ClientContext() unsafe.Pointer

func (URLRequest) Destroy

func (r URLRequest) Destroy()

func (URLRequest) FollowRedirect

func (r URLRequest) FollowRedirect() Result

FollowRedirect Follows a pending redirect. Must only be called at most once for each invocation of URLRequestCallbackHandler.OnRedirectReceived().

func (URLRequest) GetStatus

func (r URLRequest) GetStatus(listener URLRequestStatusListener)

GetStatus Queries the status of the request. @param listener a URLRequestStatusListener that will be invoked with

the request's current status. Listener will be invoked
back on the Executor passed in when the request was
created.

func (URLRequest) InitWithParams

func (r URLRequest) InitWithParams(engine Engine, url string, params URLRequestParams, callback URLRequestCallback, executor Executor) Result

InitWithParams Initialized URLRequest to |url| with |params|. All methods of |callback| for request will be invoked on |executor|. The |executor| must not run tasks on the thread calling Executor.Execute() to prevent blocking networking operations and causing failure RESULTs during shutdown.

@param engine Engine to process the request. @param url URL for the request. @param params additional parameters for the request, like headers and priority. @param callback Callback that gets invoked on different events. @param executor Executor on which all callbacks will be invoked.

func (URLRequest) IsDone

func (r URLRequest) IsDone() bool

IsDone Returns true if the request was successfully started and is now finished (completed, canceled, or failed).

func (URLRequest) Read

func (r URLRequest) Read(buffer Buffer) Result

Read Attempts to read part of the response body into the provided buffer. Must only be called at most once in response to each invocation of the URLRequestCallbackHandler.OnResponseStarted() and URLRequestCallbackHandler.OnReadCompleted()} methods of the URLRequestCallbackHandler. Each call will result in an asynchronous call to either the URLRequestCallbackHandler.OnReadCompleted() method if data is read, its URLRequestCallbackHandler.OnSucceeded() method if there's no more data to read, or its URLRequestCallbackHandler.OnFailed() method if there's an error. This method transfers ownership of |buffer| to Cronet, and app should not access it until one of these callbacks is invoked.

@param buffer to write response body to. The app must not read or

modify buffer's position, limit, or data between its position and
limit until the request calls back into the URLRequestCallbackHandler.

func (URLRequest) SetClientContext

func (r URLRequest) SetClientContext(context unsafe.Pointer)

func (URLRequest) Start

func (r URLRequest) Start() Result

Start starts the request, all callbacks go to URLRequestCallbackHandler. May only be called once. May not be called if Cancel() has been called.

type URLRequestCallback

type URLRequestCallback struct {
	// contains filtered or unexported fields
}

URLRequestCallback is used to receive callbacks from URLRequest.

func NewURLRequestCallback

func NewURLRequestCallback(handler URLRequestCallbackHandler) URLRequestCallback

func (URLRequestCallback) ClientContext

func (c URLRequestCallback) ClientContext() unsafe.Pointer

func (URLRequestCallback) Destroy

func (c URLRequestCallback) Destroy()

func (URLRequestCallback) SetClientContext

func (c URLRequestCallback) SetClientContext(context unsafe.Pointer)

type URLRequestCallbackHandler

type URLRequestCallbackHandler interface {
	// OnRedirectReceived is invoked whenever a redirect is encountered.
	OnRedirectReceived(self URLRequestCallback, request URLRequest, info URLResponseInfo, newLocationUrl string)

	// OnResponseStarted is invoked when the final set of headers, after all redirects, is received.
	OnResponseStarted(self URLRequestCallback, request URLRequest, info URLResponseInfo)

	// OnReadCompleted is invoked whenever part of the response body has been read.
	OnReadCompleted(self URLRequestCallback, request URLRequest, info URLResponseInfo, buffer Buffer, bytesRead int64)

	// OnSucceeded is invoked when request is completed successfully.
	OnSucceeded(self URLRequestCallback, request URLRequest, info URLResponseInfo)

	// OnFailed is invoked if request failed for any reason after URLRequest.Start().
	OnFailed(self URLRequestCallback, request URLRequest, info URLResponseInfo, error Error)

	// OnCanceled is invoked if request was canceled via URLRequest.Cancel().
	OnCanceled(self URLRequestCallback, request URLRequest, info URLResponseInfo)
}

URLRequestCallbackHandler handles callbacks from URLRequest.

type URLRequestFinishedInfoFinishedReason

type URLRequestFinishedInfoFinishedReason int

URLRequestFinishedInfoFinishedReason The reason why the request finished.

const (
	// URLRequestFinishedInfoFinishedReasonSucceeded
	// The request succeeded.
	URLRequestFinishedInfoFinishedReasonSucceeded URLRequestFinishedInfoFinishedReason = 0

	// URLRequestFinishedInfoFinishedReasonFailed
	// The request failed or returned an error.
	URLRequestFinishedInfoFinishedReasonFailed URLRequestFinishedInfoFinishedReason = 1

	// URLRequestFinishedInfoFinishedReasonCanceled
	// The request was canceled.
	URLRequestFinishedInfoFinishedReasonCanceled URLRequestFinishedInfoFinishedReason = 2
)

type URLRequestFinishedInfoListener

type URLRequestFinishedInfoListener struct {
	// contains filtered or unexported fields
}

URLRequestFinishedInfoListener is called when a request finishes.

func (URLRequestFinishedInfoListener) ClientContext

func (l URLRequestFinishedInfoListener) ClientContext() unsafe.Pointer

func (URLRequestFinishedInfoListener) Destroy

func (l URLRequestFinishedInfoListener) Destroy()

func (URLRequestFinishedInfoListener) SetClientContext

func (l URLRequestFinishedInfoListener) SetClientContext(context unsafe.Pointer)

type URLRequestFinishedInfoListenerOnRequestFinishedFunc

type URLRequestFinishedInfoListenerOnRequestFinishedFunc func(listener URLRequestFinishedInfoListener, requestInfo RequestFinishedInfo, responseInfo URLResponseInfo, error Error)

URLRequestFinishedInfoListenerOnRequestFinishedFunc is called when a request finishes.

type URLRequestHandler

type URLRequestHandler interface {
	InitWithParams(self URLRequest, engine Engine, url string, params URLRequestParams, callback URLRequestCallback, executor Executor) Result
	Start(self URLRequest) Result
	FollowRedirect(self URLRequest) Result
	Read(self URLRequest, buffer Buffer) Result
	Cancel(self URLRequest)
	IsDone(self URLRequest) bool
	GetStatus(self URLRequest, listener URLRequestStatusListener)
}

URLRequestHandler is an interface for custom URLRequest implementations (for testing/mocking).

type URLRequestParams

type URLRequestParams struct {
	// contains filtered or unexported fields
}

URLRequestParams contains parameters for initializing a URLRequest.

func NewURLRequestParams

func NewURLRequestParams() URLRequestParams

func (URLRequestParams) AddAnnotation

func (p URLRequestParams) AddAnnotation(annotation unsafe.Pointer)

AddAnnotation Associates the annotation object with this request. May add more than one. Passed through to a RequestFinishedInfoListener.

func (URLRequestParams) AddHeader

func (p URLRequestParams) AddHeader(header HTTPHeader)

AddHeader Add HTTP header for this request

func (URLRequestParams) AllocDirectExecutor

func (p URLRequestParams) AllocDirectExecutor() bool

func (URLRequestParams) AnnotationAt

func (p URLRequestParams) AnnotationAt(index int) unsafe.Pointer

func (URLRequestParams) AnnotationSize

func (p URLRequestParams) AnnotationSize() int

func (URLRequestParams) ClearAnnotations

func (p URLRequestParams) ClearAnnotations()

func (URLRequestParams) ClearHeaders

func (p URLRequestParams) ClearHeaders()

func (URLRequestParams) Destroy

func (p URLRequestParams) Destroy()

func (URLRequestParams) DisableCache

func (p URLRequestParams) DisableCache() bool

func (URLRequestParams) HeaderAt

func (p URLRequestParams) HeaderAt(index int) HTTPHeader

func (URLRequestParams) HeaderSize

func (p URLRequestParams) HeaderSize() int

func (URLRequestParams) Idempotency

func (URLRequestParams) Method

func (p URLRequestParams) Method() string

func (URLRequestParams) Priority

func (URLRequestParams) RequestFinishedExecutor

func (p URLRequestParams) RequestFinishedExecutor() Executor

func (URLRequestParams) RequestFinishedListener

func (p URLRequestParams) RequestFinishedListener() URLRequestFinishedInfoListener

func (URLRequestParams) SetAllowDirectExecutor

func (p URLRequestParams) SetAllowDirectExecutor(allow bool)

SetAllowDirectExecutor Marks that the executors this request will use to notify callbacks (for UploadDataProvider and URLRequestCallback) is intentionally performing inline execution without switching to another thread.

<p><b>Warning:</b> This option makes it easy to accidentally block the network thread. It should not be used if your callbacks perform disk I/O, acquire locks, or call into other code you don't carefully control and audit.

func (URLRequestParams) SetDisableCache

func (p URLRequestParams) SetDisableCache(disable bool)

SetDisableCache Disables cache for the request. If context is not set up to use cache, this call has no effect.

func (URLRequestParams) SetIdempotency

func (p URLRequestParams) SetIdempotency(idempotency URLRequestParamsIdempotency)

SetIdempotency Idempotency of the request, which determines that if it is safe to enable 0-RTT for the Cronet request. By default, 0-RTT is only enabled for safe HTTP methods, i.e., GET, HEAD, OPTIONS, and TRACE. For other methods, enabling 0-RTT may cause security issues since a network observer can replay the request. If the request has any side effects, those effects can happen multiple times. It is only safe to enable the 0-RTT if it is known that the request is idempotent.

func (URLRequestParams) SetMethod

func (p URLRequestParams) SetMethod(method string)

SetMethod The HTTP method verb to use for this request.

The default when this value is not set is "GET" if the request has no body or "POST" if it does.

Allowed methods are "GET", "HEAD", "DELETE", "POST", "PUT" and "CONNECT".

func (URLRequestParams) SetPriority

func (p URLRequestParams) SetPriority(priority URLRequestParamsRequestPriority)

SetPriority Priority of the request which should be one of the URLRequestParamsRequestPriority values.

func (URLRequestParams) SetRequestFinishedExecutor

func (p URLRequestParams) SetRequestFinishedExecutor(executor Executor)

SetRequestFinishedExecutor The Executor used to run the RequestFinishedListener.

Ownership is **not** taken.

Similar to RequestFinishedListener, the app may destroy RequestFinishedExecutor in or after URLRequestFinishedInfoListenerOnRequestFinishedFunc

It's also OK to destroy RequestFinishedExecutor in or after one of {@link URLRequestCallbackHandler.OnCanceled()}, {@link URLRequestCallbackHandler.OnFailed()} or {@link URLRequestCallbackHandler.OnSucceeded()}.

Of course, both of these are only true if {@code request_finished_executor} isn't being used for anything else that might start running in the future.

func (URLRequestParams) SetRequestFinishedListener

func (p URLRequestParams) SetRequestFinishedListener(listener URLRequestFinishedInfoListener)

SetRequestFinishedListener A listener that gets invoked at the end of each request.

The listener is invoked with the request finished info on RequestFinishedExecutor, which must be set.

The listener is called before URLRequestCallbackHandler.OnCanceled(), URLRequestCallbackHandler.OnFailed() or URLRequestCallbackHandler.OnSucceeded() is called -- note that if RequestFinishedListener runs the listener asynchronously, the actual call to the listener may happen after a {@code URLRequestCallbackHandler} method is called.

Ownership is **not** taken.

Assuming the listener won't run again (there are no pending requests with the listener attached, either via Engine or @code URLRequest), the app may destroy it once its URLRequestFinishedInfoListenerOnRequestFinishedFunc has started, even inside that method.

func (URLRequestParams) SetUploadDataExecutor

func (p URLRequestParams) SetUploadDataExecutor(executor Executor)

SetUploadDataExecutor Upload data provider executor that will be used to invoke uploadDataProvider.

func (URLRequestParams) SetUploadDataProvider

func (p URLRequestParams) SetUploadDataProvider(provider UploadDataProvider)

SetUploadDataProvider Upload data provider. Setting this value switches method to "POST" if not explicitly set. Starting the request will fail if a Content-Type header is not set.

func (URLRequestParams) UploadDataExecutor

func (p URLRequestParams) UploadDataExecutor() Executor

func (URLRequestParams) UploadDataProvider

func (p URLRequestParams) UploadDataProvider() UploadDataProvider

type URLRequestParamsIdempotency

type URLRequestParamsIdempotency int

URLRequestParamsIdempotency specifies idempotency of a request.

const (
	URLRequestParamsIdempotencyDefaultIdempotency URLRequestParamsIdempotency = 0
	URLRequestParamsIdempotencyIdempotent         URLRequestParamsIdempotency = 1
	URLRequestParamsIdempotencyNotIdempotent      URLRequestParamsIdempotency = 2
)

type URLRequestParamsRequestPriority

type URLRequestParamsRequestPriority int

URLRequestParamsRequestPriority specifies request priority level.

const (
	// URLRequestParamsRequestPriorityIdle
	// Lowest request priority.
	URLRequestParamsRequestPriorityIdle URLRequestParamsRequestPriority = 0

	// URLRequestParamsRequestPriorityLowest
	// Very low request priority.
	URLRequestParamsRequestPriorityLowest URLRequestParamsRequestPriority = 1

	// URLRequestParamsRequestPriorityLow
	// Low request priority.
	URLRequestParamsRequestPriorityLow URLRequestParamsRequestPriority = 2

	// URLRequestParamsRequestPriorityMedium
	// Medium request priority. This is the default priority given to the request.
	URLRequestParamsRequestPriorityMedium URLRequestParamsRequestPriority = 3

	// URLRequestParamsRequestPriorityHighest
	// Highest request priority.
	URLRequestParamsRequestPriorityHighest URLRequestParamsRequestPriority = 4
)

type URLRequestStatusListener

type URLRequestStatusListener struct {
	// contains filtered or unexported fields
}

URLRequestStatusListener receives status updates for a URLRequest.

func (URLRequestStatusListener) ClientContext

func (l URLRequestStatusListener) ClientContext() unsafe.Pointer

func (URLRequestStatusListener) Destroy

func (l URLRequestStatusListener) Destroy()

func (URLRequestStatusListener) SetClientContext

func (l URLRequestStatusListener) SetClientContext(context unsafe.Pointer)

type URLRequestStatusListenerOnStatusFunc

type URLRequestStatusListenerOnStatusFunc func(self URLRequestStatusListener, status URLRequestStatusListenerStatus)

URLRequestStatusListenerOnStatusFunc is called with the status of a URL request.

type URLRequestStatusListenerStatus

type URLRequestStatusListenerStatus int

URLRequestStatusListenerStatus specifies the status of a URL request.

const (
	URLRequestStatusListenerStatusInvalid                     URLRequestStatusListenerStatus = -1
	URLRequestStatusListenerStatusIdle                        URLRequestStatusListenerStatus = 0
	URLRequestStatusListenerStatusWaitingForStalledSocketPool URLRequestStatusListenerStatus = 1
	URLRequestStatusListenerStatusWaitingForAvailableSocket   URLRequestStatusListenerStatus = 2
	URLRequestStatusListenerStatusWaitingForDelegate          URLRequestStatusListenerStatus = 3
	URLRequestStatusListenerStatusWaitingForCache             URLRequestStatusListenerStatus = 4
	URLRequestStatusListenerStatusDownloadingPacFile          URLRequestStatusListenerStatus = 5
	URLRequestStatusListenerStatusResolvingProxyForURL        URLRequestStatusListenerStatus = 6
	URLRequestStatusListenerStatusResolvingHostInPacFile      URLRequestStatusListenerStatus = 7
	URLRequestStatusListenerStatusEstablishingProxyTunnel     URLRequestStatusListenerStatus = 8
	URLRequestStatusListenerStatusResolvingHost               URLRequestStatusListenerStatus = 9
	URLRequestStatusListenerStatusConnecting                  URLRequestStatusListenerStatus = 10
	URLRequestStatusListenerStatusSSLHandshake                URLRequestStatusListenerStatus = 11
	URLRequestStatusListenerStatusSendingRequest              URLRequestStatusListenerStatus = 12
	URLRequestStatusListenerStatusWaitingForResponse          URLRequestStatusListenerStatus = 13
	URLRequestStatusListenerStatusReadingResponse             URLRequestStatusListenerStatus = 14
)

type URLResponseInfo

type URLResponseInfo struct {
	// contains filtered or unexported fields
}

URLResponseInfo contains response information for a URLRequest.

func NewURLResponseInfo

func NewURLResponseInfo() URLResponseInfo

func (URLResponseInfo) AddHeader

func (i URLResponseInfo) AddHeader(header HTTPHeader)

func (URLResponseInfo) AddURLChain

func (i URLResponseInfo) AddURLChain(url string)

func (URLResponseInfo) Cached

func (i URLResponseInfo) Cached() bool

Cached true if the response came from the cache, including requests that were revalidated over the network before being retrieved from the cache, failed otherwise.

func (URLResponseInfo) ClearHeaders

func (i URLResponseInfo) ClearHeaders()

func (URLResponseInfo) ClearURLChain

func (i URLResponseInfo) ClearURLChain()

func (URLResponseInfo) Destroy

func (i URLResponseInfo) Destroy()

func (URLResponseInfo) HeaderAt

func (i URLResponseInfo) HeaderAt(index int) HTTPHeader

func (URLResponseInfo) HeaderSize

func (i URLResponseInfo) HeaderSize() int

HeaderSize list size of response header field and value pairs. The headers are in the same order they are received over the wire.

func (URLResponseInfo) NegotiatedProtocol

func (i URLResponseInfo) NegotiatedProtocol() string

NegotiatedProtocol is the protocol (for example 'quic/1+spdy/3') negotiated with the server. An empty string if no protocol was negotiated, the protocol is not known, or when using plain HTTP or HTTPS.

func (URLResponseInfo) ProxyServer

func (i URLResponseInfo) ProxyServer() string

ProxyServer is the proxy server that was used for the request.

func (URLResponseInfo) ReceivedByteCount

func (i URLResponseInfo) ReceivedByteCount() int64

ReceivedByteCount is a minimum count of bytes received from the network to process this request. This count may ignore certain overheads (for example IP and TCP/UDP framing, SSL handshake and framing, proxy handling). This count is taken prior to decompression (for example GZIP and Brotli) and includes headers and data from all redirects.

func (URLResponseInfo) SetCached

func (i URLResponseInfo) SetCached(cached bool)

func (URLResponseInfo) SetNegotiatedProtocol

func (i URLResponseInfo) SetNegotiatedProtocol(protocol string)

func (URLResponseInfo) SetProxyServer

func (i URLResponseInfo) SetProxyServer(proxy string)

func (URLResponseInfo) SetReceivedByteCount

func (i URLResponseInfo) SetReceivedByteCount(count int64)

func (URLResponseInfo) SetStatusCode

func (i URLResponseInfo) SetStatusCode(code int32)

func (URLResponseInfo) SetStatusText

func (i URLResponseInfo) SetStatusText(text string)

func (URLResponseInfo) SetURL

func (i URLResponseInfo) SetURL(url string)

func (URLResponseInfo) StatusCode

func (i URLResponseInfo) StatusCode() int

StatusCode is the HTTP status code. When a resource is retrieved from the cache, whether it was revalidated or not, the original status code is returned.

func (URLResponseInfo) StatusText

func (i URLResponseInfo) StatusText() string

StatusText is the HTTP status text of the status line. For example, if the request received a "HTTP/1.1 200 OK" response, this method returns "OK".

func (URLResponseInfo) URL

func (i URLResponseInfo) URL() string

The URL the response is for. This is the URL after following redirects, so it may not be the originally requested URL

func (URLResponseInfo) URLChainAt

func (i URLResponseInfo) URLChainAt(index int) string

func (URLResponseInfo) URLChainSize

func (i URLResponseInfo) URLChainSize() int

URLChainSize The URL chain. The first entry is the originally requested URL; the following entries are redirects followed.

type UploadDataProvider

type UploadDataProvider struct {
	// contains filtered or unexported fields
}

UploadDataProvider provides upload data to a URLRequest.

func NewUploadDataProvider

func NewUploadDataProvider(handler UploadDataProviderHandler) UploadDataProvider

func (UploadDataProvider) ClientContext

func (p UploadDataProvider) ClientContext() unsafe.Pointer

func (UploadDataProvider) Destroy

func (p UploadDataProvider) Destroy()

func (UploadDataProvider) SetClientContext

func (p UploadDataProvider) SetClientContext(context unsafe.Pointer)

type UploadDataProviderHandler

type UploadDataProviderHandler interface {
	// Length
	// If this is a non-chunked upload, returns the length of the upload. Must
	// always return -1 if this is a chunked upload.
	Length(self UploadDataProvider) int64

	// Read
	// Reads upload data into |buffer|. Each call of this method must be followed be a
	// single call, either synchronous or asynchronous, to
	// UploadDataSink.OnReadSucceeded() on success
	// or UploadDataSink.OnReadError() on failure. Neither read nor rewind
	// will be called until one of those methods or the other is called. Even if
	// the associated UrlRequest is canceled, one or the other must
	// still be called before resources can be safely freed.
	//
	// @param sink The object to notify when the read has completed,
	//            successfully or otherwise.
	// @param buffer The buffer to copy the read bytes into.
	Read(self UploadDataProvider, sink UploadDataSink, buffer Buffer)

	// Rewind
	// Rewinds upload data. Each call must be followed be a single
	// call, either synchronous or asynchronous, to
	// UploadDataSink.OnRewindSucceeded() on success or
	// UploadDataSink.OnRewindError() on failure. Neither read nor rewind
	// will be called until one of those methods or the other is called.
	// Even if the associated UrlRequest is canceled, one or the other
	// must still be called before resources can be safely freed.
	//
	// If rewinding is not supported, this should call
	// UploadDataSink.OnRewindError(). Note that rewinding is required to
	// follow redirects that preserve the upload body, and for retrying when the
	// server times out stale sockets.
	//
	// @param sink The object to notify when the rewind operation has
	//         completed, successfully or otherwise.
	Rewind(self UploadDataProvider, sink UploadDataSink)

	// Close
	// Called when this UploadDataProvider is no longer needed by a request, so that resources
	// (like a file) can be explicitly released.
	Close(self UploadDataProvider)
}

UploadDataProviderHandler is the interface that must be implemented to provide upload data.

type UploadDataSink

type UploadDataSink struct {
	// contains filtered or unexported fields
}

UploadDataSink is used by UploadDataProvider to signal events.

func NewUploadDataSinkWith

func NewUploadDataSinkWith(handler UploadDataSinkHandler) UploadDataSink

NewUploadDataSinkWith creates a new UploadDataSink with custom handler (for testing/mocking).

func (UploadDataSink) ClientContext

func (s UploadDataSink) ClientContext() unsafe.Pointer

func (UploadDataSink) OnReadError

func (s UploadDataSink) OnReadError(message string)

OnReadError Called by UploadDataProviderHandler when a read fails. @param message to pass on to URLRequestCallbackHandler.OnFailed().

func (UploadDataSink) OnReadSucceeded

func (s UploadDataSink) OnReadSucceeded(bytesRead int64, finalChunk bool)

OnReadSucceeded

Called by UploadDataProviderHandler when a read succeeds.

@param bytesRead number of bytes read into buffer passed to UploadDataProviderHandler.Read(). @param finalChunk For chunked uploads, |true| if this is the final

read. It must be |false| for non-chunked uploads.

func (UploadDataSink) OnRewindError

func (s UploadDataSink) OnRewindError(message string)

OnRewindError Called by UploadDataProviderHandler when a rewind fails, or if rewinding uploads is not supported. * @param message to pass on to URLRequestCallbackHandler.OnFailed().

func (UploadDataSink) OnRewindSucceeded

func (s UploadDataSink) OnRewindSucceeded()

OnRewindSucceeded Called by UploadDataProviderHandler when a rewind succeeds.

func (UploadDataSink) SetClientContext

func (s UploadDataSink) SetClientContext(context unsafe.Pointer)

type UploadDataSinkHandler

type UploadDataSinkHandler interface {
	OnReadSucceeded(self UploadDataSink, bytesRead uint64, finalChunk bool)
	OnReadError(self UploadDataSink, errorMessage string)
	OnRewindSucceeded(self UploadDataSink)
	OnRewindError(self UploadDataSink, errorMessage string)
}

UploadDataSinkHandler is an interface for custom UploadDataSink implementations (for testing/mocking).

Directories

Path Synopsis
all module
cmd
build-naive command
lib
linux_amd64 module

Jump to

Keyboard shortcuts

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