Running HTTP/2 client.
Modulehttp2-5.3.10Haskell2010
Network.HTTP2.Client
HTTP/2 client library.
Example:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Main where
import qualified Data.ByteString.Char8 as C8
import Network.HTTP.Types
import Network.Run.TCP (runTCPClient) -- network-run
import Control.Concurrent.Async
import qualified Control.Exception as E
import Network.HTTP2.Client
serverName :: String
serverName = "127.0.0.1"
main :: IO ()
main = runTCPClient serverName "80" $ runHTTP2Client serverName
where
cliconf host = defaultClientConfig { authority = host }
runHTTP2Client host s = E.bracket (allocSimpleConfig s 4096)
freeSimpleConfig
(\conf -> run (cliconf host) conf client)
client :: Client ()
client sendRequest _aux = do
let req0 = requestNoBody methodGet "/" []
client0 = sendRequest req0 $ \rsp -> do
print rsp
getResponseBodyChunk rsp >>= C8.putStrLn
req1 = requestNoBody methodGet "/foo" []
client1 = sendRequest req1 $ \rsp -> do
print rsp
getResponseBodyChunk rsp >>= C8.putStrLn
ex <- E.try $ concurrently_ client0 client1
case ex of
Left e -> print (e :: HTTP2Error)
Right () -> putStrLn "OK"- 25 types
- 38 values
- Packagehttp2-5.3.10
- Exports77
- LanguageHaskell2010
- LicenceBSD-3-Clause
- SourceClient.hs
Runner
1 declarationClient configuration
7 declarationsClient configuration
Instances2Eq, Show
Eq ClientConfigDefined in http2-5.3.10 · Network.HTTP2.Client.RunShow ClientConfigDefined in http2-5.3.10 · Network.HTTP2.Client.Run
The default client config.
The authority field will be used to set the HTTP2 :authority
pseudo-header. In most cases you will want to override it to be equal to
host.
Further background on authority:
RFC 3986 also
allows host:port, and most servers will accept this too. However, when
using TLS, many servers will expect the TLS SNI server name and the
:authority pseudo-header to be equal, and for TLS SNI the server name
should not include the port. Note that HTTP2 explicitly disallows using
userinfo@ as part of the authority.
defaultClientConfigClientConfig {scheme = "http", authority = "localhost", cacheLimit = 64, connectionWindowSize = 16777216, settings = Settings {headerTableSize = 4096, enablePush = True, maxConcurrentStreams = Just 64, initialWindowSize = 262144, maxFrameSize = 16384, maxHeaderListSize = Nothing, pingRateLimit = 10, emptyFrameRateLimit = 4, settingsRateLimit = 4, rstRateLimit = 4}}
https or http
Server name
The maximum number of incoming streams on the net
The window size of connection.
Settings
HTTP/2 setting
8 declarationsHTTP/2 settings. See https://datatracker.ietf.org/doc/html/rfc9113#name-defined-settings.
The default settings.
defaultSettingsSettings {headerTableSize = 4096, enablePush = True, maxConcurrentStreams = Just 64, initialWindowSize = 262144, maxFrameSize = 16384, maxHeaderListSize = Nothing, pingRateLimit = 10, emptyFrameRateLimit = 4, settingsRateLimit = 4, rstRateLimit = 4}
SETTINGS_HEADER_TABLE_SIZE
SETTINGS_ENABLE_PUSH
SETTINGS_MAX_CONCURRENT_STREAMS
SETTINGS_INITIAL_WINDOW_SIZE
SETTINGS_MAX_FRAME_SIZE
SETTINGS_MAX_HEADER_LIST_SIZE
Rate limits
Maximum number of pings allowed per second (CVE-2019-9512)
Maximum number of settings frames allowed per second (CVE-2019-9515)
Maximum number of empty data frames allowed per second (CVE-2019-9518)
Maximum number of reset frames allowed per second (CVE-2023-44487)
Common configuration
40 declarationsHTTP/2 configuration.
Constructors
ConfigconfWriteBuffer :: BufferThis is used only by frameSender. This MUST be freed after frameSender is terminated.
confBufferSize :: BufferSizeThe size of the write buffer. We assume that the read buffer is the same size. So, this value is announced via SETTINGS_MAX_FRAME_SIZE to the peer.
confSendAll :: ByteString -> IO ()confReadN :: Int -> IO ByteStringconfPositionReadMaker :: PositionReadMakerconfTimeoutManager :: ManagerconfMySockAddr :: SockAddrThis is copied into Aux, if exist, on server.
confPeerSockAddr :: SockAddrThis is copied into Aux, if exist, on server.
Making simple configuration whose IO is not efficient. A write buffer is allocated internally. WAI timeout manger is initialized with 30_000_000 microseconds.
Making simple configuration whose IO is not efficient. A write buffer is allocated internally. The third argument is microseconds to initialize WAI timeout manager.
Deallocating the resource of the simple configuration.
Client type.
Request from client.
Response from server.
Additional information.
How many streams can be created without blocking.
Either the next trailers maker or final trailers.
Constructors
Trailers maker. A chunks of the response body is passed with Just. The maker should update internal state with the ByteString and return the next trailers maker. When response body reaches its end, Nothing is passed and the maker should generate trailers. An example:
{-# LANGUAGE BangPatterns #-}
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as C8
import Crypto.Hash (Context, SHA1) -- cryptonite
import qualified Crypto.Hash as CH
-- Strictness is important for Context.
trailersMaker :: Context SHA1 -> Maybe ByteString -> IO NextTrailersMaker
trailersMaker ctx Nothing = return $ Trailers [("X-SHA1", sha1)]
where
!sha1 = C8.pack $ show $ CH.hashFinalize ctx
trailersMaker ctx (Just bs) = return $ NextTrailersMaker $ trailersMaker ctx'
where
!ctx' = CH.hashUpdate ctx bsUsage example:
let h2rsp = responseFile ...
maker = trailersMaker (CH.hashInit :: Context SHA1)
h2rsp' = setResponseTrailersMaker h2rsp makerTrailersMake to create no trailers.
Authority.
How many bytes to read
Offset for file.
File specification.
Constructors
Constructors
OutBodyIfaceoutBodyUnmask :: forall x. IO x -> IO xUnmask exceptions in the thread spawned for the request body
This is used in the client: we spawn the new thread for the request body with exceptions masked, and provide the body of OutBodyStreamingIface with a callback to unmask them again (typically after installing an exception handler).
Unmasking in the server is a no-op, as here the scope of the thread that is spawned for the server is the entire handler, not just the response streaming body.
outBodyPush :: Builder -> IO ()Push a new chunk
In
http2, there is no direct correspondence between chunks and the resultingDATAframes sent: the chunks are collected (written to an internal write buffer) until we can fill a frame.See also outBodyFlush.
outBodyPushFinal :: Builder -> IO ()Push the final chunk
Using this function instead of outBodyPush can be used to guarantee that the final HTTP2 DATA frame is marked end-of-stream; with outBodyPush it may happen that an additional empty DATA frame is used for this purpose. Additionally, after calling this function, outBodyCancel will be a no-op.
outBodyCancel :: Maybe SomeException -> IO ()Cancel the stream
Sends a
RST_STREAMto the peer. If cancelling as the result of an exception, a Just should be provided which specifies the exception which will be stored locally as the reason for cancelling the stream; in this case, the error code sent with theRST_STREAMwill beINTERNAL_ERROR(see https://datatracker.ietf.org/doc/html/rfc7540#section-7). If Nothing is given, the error code will beCANCEL.If there is a partially constructed
DATAframe at the time of cancellation, this frame is discarded. If this is undesirable, you should call outBodyFlush prior to cancelling.outBodyFlush :: IO ()Flush
This can be used to emit a DATA frame with the data collected so far (using outBodyPush), even if that DATA frame has not yet reached the maximum frame size. Calling outBodyFlush unnecessarily can therefore result in excessive overhead from frame headers.
If no data is available to send, this is a no-op.
Path.
"http" or "https".
HTTP method (flat ByteString type).
Making a position read and its closer.
Position read for files.
Position read based on Handle.
Reading n bytes.
Naive implementation for readN.
NOTE: This function is intended to be used by a single thread only. (It is probably quite rare anyway to want concurrent reads from the same network socket.)
Reading a chunk of the response body. An empty ByteString returned when finished.
Generalization of getResponseBodyChunk which also returns if the ByteString is the final one
Reading response trailers. This function must be called after getResponseBodyChunk returns an empty.
Creating request with builder.
Creating request with file.
Creating request without body.
Creating request with streaming.
Generalized version of requestStreaming,
Like requestStreaming, but run the action with exceptions masked
Getting the body size from a response.
Getting the headers from a response.
Getting the status of a response.
Setting TrailersMaker to Response.
Send a request and receive its response.
Error
17 declarationsThe connection error or the stream error. Stream errors are treated as connection errors since there are no good recovery ways. ErrorCode in connection errors should be the highest stream identifier but in this implementation it identifies the stream that caused this error.
Instances2Show, Exception
Show HTTP2ErrorDefined in http2-5.3.10 · Network.HTTP2.H2.TypesException HTTP2ErrorDefined in http2-5.3.10 · Network.HTTP2.H2.Types
The type for error code. See https://www.rfc-editor.org/rfc/rfc9113#ErrorCodes.