cronet

package module
v0.0.0-...-90f0bb3 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2022 License: GPL-2.0 Imports: 14 Imported by: 0

README

cronet-go

Cronet is the Chromium network stack made available to Android apps as a library. Cronet takes advantage of multiple technologies that reduce the latency and increase the throughput of the network requests that your app needs to work.

The Cronet Library handles the requests of apps used by millions of people on a daily basis, such as YouTube, Google App, Google Photos, and Maps - Navigation & Transit.

This experimental project ported Cronet to golang with NaiveProxy support. To learn how to use the Cronet Library in your app, see the transport and naive-go example.

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
}

BidirectionalConn is a wrapper from BidirectionalStream to net.Conn

func (*BidirectionalConn) Close

func (c *BidirectionalConn) Close() error

Close implements io.Closer

func (*BidirectionalConn) Done

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

Done implements context.Context

func (*BidirectionalConn) Err

func (c *BidirectionalConn) Err() error

Err implements context.Context

func (*BidirectionalConn) LocalAddr

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

LocalAddr implements net.Conn

func (*BidirectionalConn) Read

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

Read implements io.Reader

func (*BidirectionalConn) RemoteAddr

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

RemoteAddr implements net.Conn

func (*BidirectionalConn) SetDeadline

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

SetDeadline implements net.Conn

func (*BidirectionalConn) SetReadDeadline

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

SetReadDeadline implements net.Conn

func (*BidirectionalConn) SetWriteDeadline

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

SetWriteDeadline implements net.Conn

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) Write

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

Write implements io.Writer

type BidirectionalStream

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

BidirectionalStream Opaque object representing 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.

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 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 (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) 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 app-provided callback passed to Buffer.InitWithDataAndCallback that gets invoked when Buffer is destroyed.

func NewBufferCallback

func NewBufferCallback(callbackFunc BufferCallbackFunc) BufferCallback

func (BufferCallback) Destroy

func (c BufferCallback) Destroy()

type BufferCallbackFunc

type BufferCallbackFunc func(callback BufferCallback, buffer Buffer)

BufferCallbackFunc invoked when |buffer| is destroyed so its app-allocated |data| can be freed. If a URLRequest has ownership of a Buffer and the UrlRequest is destroyed (e.g. URLRequest.Destroy() is called), then Cronet will call BufferCallbackFunc().

type DateTime

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

DateTime Represents a date and time expressed as the number of milliseconds since the UNIX epoch.

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 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 (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) 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) 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 EngineParams

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

EngineParams is the parameters for Engine, which allows its configuration before start. Configuration options are set on the EngineParams and then Engine.StartWithParams is called to start the Engine.

func NewEngineParams

func NewEngineParams() EngineParams

func (EngineParams) AccentLanguage

func (p EngineParams) AccentLanguage() 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() HTTPCacheMode

func (EngineParams) NetworkThreadPriority

func (p EngineParams) NetworkThreadPriority() int

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) SetAccentLanguage

func (p EngineParams) SetAccentLanguage(acceptLanguage string)

SetAccentLanguage 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) 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) SetExperimentalOptions

func (p EngineParams) SetExperimentalOptions(options string)

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

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 HTTPCacheMode)

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

func (EngineParams) SetNetworkThreadPriority

func (p EngineParams) SetNetworkThreadPriority(priority int)

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) SetStoragePath

func (p EngineParams) SetStoragePath(storagePath string)

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

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 Error

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

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

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).

type ErrorCode

type ErrorCode int
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 <a href="https://www.chromium.org/quic">
	// <a>QUIC</a> 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 |command| asynchronously.

func NewExecutor

func NewExecutor(executeFunc ExecutorExecuteFunc) Executor

func (Executor) Destroy

func (e Executor) Destroy()

func (Executor) Execute

func (e Executor) Execute(command Runnable)

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 HTTPCacheMode

type HTTPCacheMode int

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

const (
	// HTTPCacheModeDisabled Disable HTTP cache. Some data may still be temporarily stored in memory.
	HTTPCacheModeDisabled HTTPCacheMode = 0

	// HTTPCacheModeInMemory Enable in-memory HTTP cache, including HTTP data.
	HTTPCacheModeInMemory HTTPCacheMode = 1

	// HTTPCacheModeDiskNoHTTP Enable on-disk cache, excluding HTTP data.
	// |storagePath| must be set to existing directory.
	HTTPCacheModeDiskNoHTTP HTTPCacheMode = 2

	// HTTPCacheModeDisk Enable on-disk cache, including HTTP data.
	// |storagePath| must be set to existing directory.
	HTTPCacheModeDisk HTTPCacheMode = 3
)

type HTTPHeader

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

HTTPHeader is a single HTTP request or response header

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 Represents metrics collected for a single request. Most of these metrics are timestamps for events during the lifetime of the request, which can be used to build a detailed timeline for investigating performance.

Represents metrics collected for a single request. Most of these metrics are timestamps for events during the lifetime of the request, which can be used to build a detailed timeline for investigating performance.

Events happen in this order: <ol> <li>#request_start request start</li> <li>#dns_start DNS start</li> <li>#dns_end DNS end</li> <li>#connect_start connect start</li> <li>#ssl_start SSL start</li> <li>#ssl_end SSL end</li> <li>#connect_end connect end</li> <li>#sending_start sending start</li> <li>#sending_end sending end</li> <li>#response_start response start</li> <li>#request_end request end</li> </ol>

Start times are reported as the time when a request started blocking on the event, not when the event actually occurred, with the exception of push start and end. If a metric is not meaningful or not available, including cases when a request finished before reaching that stage, start and end times will be null. If no time was spent blocking on an event, start and end will be the same time.

Timestamps are recorded using a clock that is guaranteed not to run backwards. All timestamps are correct relative to the system clock at the time of request start, and taking the difference between two timestamps will give the correct difference between the events. In order to preserve this property, timestamps for events other than request start are not guaranteed to match the system clock at the times they represent.

Most timing metrics are taken from <a href="https://cs.chromium.org/chromium/src/net/base/load_timing_info.h">LoadTimingInfo</a>, which holds the information for <a href="http://w3c.github.io/navigation-timing/"></a> and <a href="https://www.w3.org/TR/resource-timing/"></a>.

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) 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) 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 PublicKeyPins

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

PublicKeyPins is a set of public keys for a given |host|. By pinning a set of public keys, |pinsSha256|, communication with |host| is required to authenticate with a certificate with a public key from the set of pinned ones. An app can pin the public key of the root certificate, any of the intermediate certificates or the end-entry certificate. Authentication will fail and secure communication will not be established if none of the public keys is present in the host's certificate chain, even if the host attempts to authenticate with a certificate allowed by the device's trusted store of certificates. * More information about the public key pinning can be found in <a href="https://tools.ietf.org/html/rfc7469">RFC 7469</a>.

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 QuicHint

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

QuicHint hint that |host| supports QUIC.

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 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
	Executor      Executor

	Proxy string
	// contains filtered or unexported fields
}

RoundTripper is a wrapper from URLRequest to http.RoundTripper

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 an interface to run commands on the Executor.

Note: In general creating Runnables should only be done by Cronet. Runnables created by the app don't have the ability to perform operations when the Runnable is being destroyed (i.e. by Cronet_Runnable_Destroy) so resource leaks are possible if the Runnable is posted to an Executor that is being shutdown with unexecuted Runnables. In controlled testing environments deallocation of associated resources can be performed in Run() if the runnable can be assumed to always be executed. */

func (Runnable) Destroy

func (r Runnable) Destroy()

func (Runnable) Run

func (r Runnable) Run()

type StreamEngine

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

StreamEngine 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(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 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 (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) 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) 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 Users of Cronet implement this interface to receive callbacks indicating the progress of a URLRequest being processed. An instance of this interface is passed in to URLRequest.InitWithParams().

Note: All methods will be invoked on the Executor passed to URLRequest.InitWithParams();

func NewURLRequestCallback

func NewURLRequestCallback(handler URLRequestCallbackHandler) URLRequestCallback

func (URLRequestCallback) Destroy

func (l URLRequestCallback) Destroy()

type URLRequestCallbackHandler

type URLRequestCallbackHandler interface {
	// OnRedirectReceived
	// Invoked whenever a redirect is encountered. This will only be invoked
	// between the call to URLRequest.Start() and
	// URLRequestCallbackHandler.OnResponseStarted().
	// The body of the redirect response, if it has one, will be ignored.
	//
	// The redirect will not be followed until the URLRequest.FollowRedirect()
	// method is called, either synchronously or asynchronously.
	//
	// @param request Request being redirected.
	// @param info Response information.
	// @param newLocationUrl Location where request is redirected.
	OnRedirectReceived(self URLRequestCallback, request URLRequest, info URLResponseInfo, newLocationUrl string)

	// OnResponseStarted
	// Invoked when the final set of headers, after all redirects, is received.
	// Will only be invoked once for each request.
	//
	// With the exception of URLRequestCallbackHandler.OnCanceled(),
	// no other URLRequestCallbackHandler method will be invoked for the request,
	// including URLRequestCallbackHandler.OnSucceeded() and
	// URLRequestCallbackHandler.OnFailed(), until URLRequest.Read() is called to attempt
	// to start reading the response body.
	//
	// @param request Request that started to get response.
	// @param info Response information.
	OnResponseStarted(self URLRequestCallback, request URLRequest, info URLResponseInfo)

	// OnReadCompleted
	// Invoked whenever part of the response body has been read. Only part of
	// the buffer may be populated, even if the entire response body has not yet
	// been consumed. This callback transfers ownership of |buffer| back to the app,
	// and Cronet guarantees not to access it.
	//
	// With the exception of URLRequestCallbackHandler.OnCanceled(),
	// no other URLRequestCallbackHandler method will be invoked for the request,
	// including URLRequestCallbackHandler.OnSucceeded() and
	// URLRequestCallbackHandler.OnFailed(), until URLRequest.Read() is called to attempt
	// to continue reading the response body.
	//
	// @param request Request that received data.
	// @param info Response information.
	// @param buffer The buffer that was passed in to URLRequest.Read(), now
	//         containing the received data.
	// @param bytesRead The number of bytes read into buffer.
	OnReadCompleted(self URLRequestCallback, request URLRequest, info URLResponseInfo, buffer Buffer, bytesRead int64)

	// OnSucceeded
	// Invoked when request is completed successfully. Once invoked, no other
	// URLRequestCallbackHandler methods will be invoked.
	//
	// Implementations of OnSucceeded() are allowed to call
	// URLRequest.Destroy(), but note that destroying request destroys info.
	//
	// @param request Request that succeeded.
	// @param info Response information. NOTE: this is owned by request.
	OnSucceeded(self URLRequestCallback, request URLRequest, info URLResponseInfo)

	// OnFailed
	// Invoked if request failed for any reason after URLRequest.Start().
	// Once invoked, no other URLRequestCallbackHandler methods will be invoked.
	// |error| provides information about the failure.
	//
	// Implementations of URLRequestCallbackHandler.OnFailed are allowed to call
	// URLRequest.Destroy(), but note that destroying request destroys info and error.
	//
	// @param request Request that failed.
	// @param info Response information. May be null if no response was
	//         received. NOTE: this is owned by request.
	// @param error information about error. NOTE: this is owned by request
	OnFailed(self URLRequestCallback, request URLRequest, info URLResponseInfo, error Error)

	// OnCanceled
	// Invoked if request was canceled via URLRequest.Cancel(). Once
	// invoked, no other UrlRequestCallback methods will be invoked.
	//
	// Implementations of URLRequestCallbackHandler.OnCanceled are allowed to call
	// URLRequest.Destroy(), but note that destroying request destroys info and error.
	//
	// @param request Request that was canceled.
	// @param info Response information. May be null if no response was
	//         received. NOTE: this is owned by request.
	OnCanceled(self URLRequestCallback, request URLRequest, info URLResponseInfo)
}

type URLRequestFinishedInfo

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

URLRequestFinishedInfo Information about a finished request.

func (URLRequestFinishedInfo) AnnotationAt

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

func (URLRequestFinishedInfo) AnnotationSize

func (i URLRequestFinishedInfo) 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 (URLRequestFinishedInfo) Destroy

func (i URLRequestFinishedInfo) Destroy()

func (URLRequestFinishedInfo) FinishedReason

FinishedReason Returns the reason why the request finished.

func (URLRequestFinishedInfo) Metrics

func (i URLRequestFinishedInfo) Metrics() Metrics

Metrics Metrics collected for this request.

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 Listens for finished requests for the purpose of collecting metrics.

func (URLRequestFinishedInfoListener) Destroy

func (l URLRequestFinishedInfoListener) Destroy()

type URLRequestFinishedInfoListenerOnRequestFinishedFunc

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

URLRequestFinishedInfoListenerOnRequestFinishedFunc Will be called in a task submitted to the Executor passed with this URLRequestFinishedInfoListener.

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

@param request_info RequestFinishedInfo for finished request.

Ownership is *not* transferred by this call, do not destroy
request_info.

URLRequest
that created it hasn't been destroyed -- **additionally**, it will
also always be valid for the duration of URLRequestFinishedInfoListenerOnRequestFinishedFunc(),
even if the URLRequest has been destroyed.

This is accomplished by ownership being shared between the
URLRequest and the code that calls this listener.

@param responseInfo A pointer to the same UrlResponseInfo passed to

URLRequestCallbackHandler.OnCanceled(), {@link
URLRequestCallbackHandler.OnFailed()} or {@link
URLRequestCallbackHandler.OnSucceeded()}. The lifetime and ownership of
requestInfo.

@param error A pointer to the same Error passed to

URLRequestCallbackHandler.OnFailed(), or null if there was no error.
The lifetime and ownership of error works the same as for
requestInfo.

/

type URLRequestParams

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

URLRequestParams Parameters for UrlRequest. Allows configuring requests before initializing them with URLRequest.InitWithParams().

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
const (
	URLRequestParamsIdempotencyDefaultIdempotency URLRequestParamsIdempotency = 0
	URLRequestParamsIdempotencyIdempotent         URLRequestParamsIdempotency = 1
	URLRequestParamsIdempotencyNotIdempotent      URLRequestParamsIdempotency = 2
)

type URLRequestParamsRequestPriority

type URLRequestParamsRequestPriority int
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 listener class used with URLRequest.GetStatus() to receive the status of a URLRequest.

func (URLRequestStatusListener) Destroy

func (l URLRequestStatusListener) Destroy()

type URLRequestStatusListenerOnStatusFunc

type URLRequestStatusListenerOnStatusFunc func(self URLRequestStatusListener, status URLRequestStatusListenerStatus)

URLRequestStatusListenerOnStatusFunc invoked on UrlRequest's Executor when request status is obtained. |status| is representing the status of the request.

type URLRequestStatusListenerStatus

type URLRequestStatusListenerStatus int
const (

	// URLRequestStatusListenerStatusInvalid
	// This state indicates that the request is completed, canceled, or is not
	// started.
	URLRequestStatusListenerStatusInvalid URLRequestStatusListenerStatus = -1

	// URLRequestStatusListenerStatusIdle
	// This state corresponds to a resource load that has either not yet begun
	// or is idle waiting for the consumer to do something to move things along
	// (e.g. when the consumer of a URLRequest has not called
	// URLRequest.read() yet).
	URLRequestStatusListenerStatusIdle URLRequestStatusListenerStatus = 0

	// URLRequestStatusListenerStatusWaitingForStalledSocketPool
	// When a socket pool group is below the maximum number of sockets allowed
	// per group, but a new socket cannot be created due to the per-pool socket
	// limit, this state is returned by all requests for the group waiting on an
	// idle connection, except those that may be serviced by a pending new
	// connection.
	URLRequestStatusListenerStatusWaitingForStalledSocketPool URLRequestStatusListenerStatus = 1

	// URLRequestStatusListenerStatusWaitingForAvailableSocket
	// When a socket pool group has reached the maximum number of sockets
	// allowed per group, this state is returned for all requests that don't
	// have a socket, except those that correspond to a pending new connection.
	URLRequestStatusListenerStatusWaitingForAvailableSocket URLRequestStatusListenerStatus = 2

	// URLRequestStatusListenerStatusWaitingForDelegate
	// This state indicates that the URLRequest delegate has chosen to block
	// this request before it was sent over the network.
	URLRequestStatusListenerStatusWaitingForDelegate URLRequestStatusListenerStatus = 3

	// URLRequestStatusListenerStatusWaitingForCache
	// This state corresponds to a resource load that is blocked waiting for
	// access to a resource in the cache. If multiple requests are made for the
	// same resource, the first request will be responsible for writing (or
	// updating) the cache entry and the second request will be deferred until
	// the first completes. This may be done to optimize for cache reuse.
	URLRequestStatusListenerStatusWaitingForCache URLRequestStatusListenerStatus = 4

	// URLRequestStatusListenerStatusDownloadingPacFile
	// This state corresponds to a resource being blocked waiting for the
	// PAC script to be downloaded.
	URLRequestStatusListenerStatusDownloadingPacFile URLRequestStatusListenerStatus = 5

	// URLRequestStatusListenerStatusResolvingProxyForUrl
	// This state corresponds to a resource load that is blocked waiting for a
	// proxy autoconfig script to return a proxy server to use.
	URLRequestStatusListenerStatusResolvingProxyForUrl URLRequestStatusListenerStatus = 6

	// URLRequestStatusListenerStatusResolvingHostInPacFile
	// This state corresponds to a resource load that is blocked waiting for a
	// proxy autoconfig script to return a proxy server to use, but that proxy
	// script is busy resolving the IP address of a host.
	URLRequestStatusListenerStatusResolvingHostInPacFile URLRequestStatusListenerStatus = 7

	// URLRequestStatusListenerStatusEstablishingProxyTunnel
	// This state indicates that we're in the process of establishing a tunnel
	// through the proxy server.
	URLRequestStatusListenerStatusEstablishingProxyTunnel URLRequestStatusListenerStatus = 8

	// URLRequestStatusListenerStatusResolvingHost
	// This state corresponds to a resource load that is blocked waiting for a
	// host name to be resolved. This could either indicate resolution of the
	// origin server corresponding to the resource or to the host name of a
	// proxy server used to fetch the resource.
	URLRequestStatusListenerStatusResolvingHost URLRequestStatusListenerStatus = 9

	// URLRequestStatusListenerStatusConnecting
	// This state corresponds to a resource load that is blocked waiting for a
	// TCP connection (or other network connection) to be established. HTTP
	// requests that reuse a keep-alive connection skip this state.
	URLRequestStatusListenerStatusConnecting URLRequestStatusListenerStatus = 10

	// URLRequestStatusListenerStatusSslHandshake
	// This state corresponds to a resource load that is blocked waiting for the
	// SSL handshake to complete.
	URLRequestStatusListenerStatusSslHandshake URLRequestStatusListenerStatus = 11

	// URLRequestStatusListenerStatusSendingRequest
	// This state corresponds to a resource load that is blocked waiting to
	// completely upload a request to a server. In the case of a HTTP POST
	// request, this state includes the period of time during which the message
	// body is being uploaded.
	URLRequestStatusListenerStatusSendingRequest URLRequestStatusListenerStatus = 12

	// URLRequestStatusListenerStatusWaitingForResponse
	// This state corresponds to a resource load that is blocked waiting for the
	// response to a network request. In the case of a HTTP transaction, this
	// corresponds to the period after the request is sent and before all of the
	// response headers have been received.
	URLRequestStatusListenerStatusWaitingForResponse URLRequestStatusListenerStatus = 13

	// URLRequestStatusListenerStatusReadingResponse
	// This state corresponds to a resource load that is blocked waiting for a
	// read to complete. In the case of a HTTP transaction, this corresponds to
	// the period after the response headers have been received and before all
	// of the response body has been downloaded. (NOTE: This state only applies
	// for an URLRequest while there is an outstanding
	// URLRequest.Read() operation.)
	URLRequestStatusListenerStatusReadingResponse URLRequestStatusListenerStatus = 14
)

type URLResponseInfo

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

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) 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) 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 The interface allowing the embedder to provide an upload body to URLRequest. It supports both non-chunked (size known in advanced) and chunked (size not known in advance) uploads. Be aware that not all servers support chunked uploads.

An upload is either always chunked, across multiple uploads if the data ends up being sent more than once, or never chunked.

func NewUploadDataProvider

func NewUploadDataProvider(handler UploadDataProviderHandler) UploadDataProvider

func (UploadDataProvider) Destroy

func (p UploadDataProvider) Destroy()

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)
}

type UploadDataSink

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

UploadDataSink

Defines callbacks methods for UploadDataProvider. All methods may be called synchronously or asynchronously, on any thread.

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.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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