-
Notifications
You must be signed in to change notification settings - Fork 0
/
http2.clj
86 lines (81 loc) · 2.56 KB
/
http2.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(ns iny.http2
(:require [clojure.tools.logging :as log]
[iny.http1 :as http1]
[iny.http2.handler :refer [http2-handler]])
(:import [io.netty.util
AsciiString
ReferenceCountUtil]
[io.netty.channel
ChannelHandler
ChannelInboundHandler
ChannelInitializer
ChannelPipeline]
[io.netty.channel.socket
SocketChannel]
[io.netty.handler.codec.http
HttpServerCodec
HttpServerUpgradeHandler
HttpServerUpgradeHandler$UpgradeCodecFactory]
[io.netty.handler.codec.http2
Http2FrameCodecBuilder
Http2CodecUtil
CleartextHttp2ServerUpgradeHandler
Http2ServerUpgradeCodec
Http2FrameCodec]))
(defn ^ChannelHandler http-fallback
[build-http-pipeline user-handler]
(reify
ChannelInboundHandler
(handlerAdded [_ _])
(handlerRemoved [_ _])
(exceptionCaught
[_ ctx ex]
(log/error ex))
(channelRegistered [_ ctx])
(channelUnregistered [_ ctx])
(channelActive [_ ctx])
(channelInactive [_ ctx])
(channelRead
[this ctx msg]
(let [pipeline (.pipeline ctx)]
;; removes the h2c-upgrade handler (no upgrade was attempted)
(build-http-pipeline pipeline user-handler)
(.fireChannelRead ctx msg)
(.remove pipeline this)))
(channelReadComplete [_ ctx])
(userEventTriggered [_ ctx event])
(channelWritabilityChanged [_ ctx])))
(let [builder (Http2FrameCodecBuilder/forServer)]
(defn ^Http2FrameCodec codec
[]
(.build builder)))
(defn upgrade-factory
[user-handler]
(reify
HttpServerUpgradeHandler$UpgradeCodecFactory
(newUpgradeCodec [_ proto]
(condp #(AsciiString/contentEquals %1 %2) proto
Http2CodecUtil/HTTP_UPGRADE_PROTOCOL_NAME
(Http2ServerUpgradeCodec.
(codec)
^"[Lio.netty.channel.ChannelHandler;"
(into-array ChannelHandler [user-handler]))))))
(defn ^CleartextHttp2ServerUpgradeHandler h2c-upgrade
[user-handler]
(let [http-codec (HttpServerCodec.)
handler (http2-handler user-handler (codec))
factory (upgrade-factory handler)]
(CleartextHttp2ServerUpgradeHandler.
http-codec
(HttpServerUpgradeHandler. http-codec factory)
handler)))
(defn server-pipeline
[^ChannelPipeline pipeline user-handler]
(.addLast
pipeline
"h2c-upgrade"
(h2c-upgrade user-handler))
(.addLast
pipeline
"http-fallback"
(http-fallback http1/server-pipeline user-handler)))