-
Notifications
You must be signed in to change notification settings - Fork 590
/
Copy pathconn.ex
1997 lines (1554 loc) · 67.3 KB
/
conn.ex
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
alias Plug.Conn.Unfetched
defmodule Plug.Conn do
@moduledoc """
The Plug connection.
This module defines a struct and the main functions for working with
requests and responses in an HTTP connection.
Note request headers are normalized to lowercase and response
headers are expected to have lowercase keys.
## Request fields
These fields contain request information:
* `host` - the requested host as a binary, example: `"www.example.com"`
* `method` - the request method as a binary, example: `"GET"`
* `path_info` - the path split into segments, example: `["hello", "world"]`
* `script_name` - the initial portion of the URL's path that corresponds to
the application routing, as segments, example: `["sub","app"]`
* `request_path` - the requested path, example: `/trailing/and//double//slashes/`
* `port` - the requested port as an integer, example: `80`
* `remote_ip` - the IP of the client, example: `{151, 236, 219, 228}`. This field
is meant to be overwritten by plugs that understand e.g. the `X-Forwarded-For`
header or HAProxy's PROXY protocol. It defaults to peer's IP
* `req_headers` - the request headers as a list, example: `[{"content-type", "text/plain"}]`.
Note all headers will be downcased
* `scheme` - the request scheme as an atom, example: `:http`
* `query_string` - the request query string as a binary, example: `"foo=bar"`
## Fetchable fields
Fetchable fields do not populate with request information until the corresponding
prefixed 'fetch_' function retrieves them, e.g., the `fetch_query_params/2` function
retrieves the `query_params` field.
If you access these fields before fetching them, they will be returned as
`Plug.Conn.Unfetched` structs.
* `body_params` - the request body params, populated through a `Plug.Parsers` parser.
* `query_params` - the request query params, populated through `fetch_query_params/2`
* `params` - the request params, the result of merging `:body_params` on top of
`:query_params` alongsaide any further changes (such as the ones done by `Plug.Router`)
## Session vs Assigns
HTTP is stateless.
This means that a server begins each request cycle with no knowledge about
the client except the request itself. Its response may include one or more
`"Set-Cookie"` headers, asking the client to send that value back in a
`"Cookie"` header on subsequent requests.
This is the basis for stateful interactions with a client, so that the server
can remember the client's name, the contents of their shopping cart, and so on.
In `Plug`, a "session" is a place to store data that persists from one request
to the next. Typically, this data is stored in a cookie using `Plug.Session.COOKIE`.
A minimal approach would be to store only a user's id in the session, then
use that during the request cycle to look up other information (in a database
or elsewhere).
More can be stored in a session cookie, but be careful: this makes requests
and responses heavier, and clients may reject cookies beyond a certain size.
Also, session cookie are not shared between a user's different browsers or devices.
If the session is stored elsewhere, such as a database, the browser only has to
store the session key and therefore more data can be stored in the session.
A typical use case would be for an authentication plug to look up a user by id
and keep the user information stored in `assigns`. Other plugs will then also
have access to it via `assigns`. This is an important point because the assign
data disappears on the next request.
To summarize: `assigns` is for storing data to be accessed during the current
request, and the session is for storing data to be accessed in subsequent
requests.
## Response fields
These fields contain response information:
* `resp_body` - the response body is an empty string by default. It is set
to nil after the response is sent, except for test connections. The response
charset defaults to "utf-8".
* `resp_cookies` - the response cookies with their name and options
* `resp_headers` - the response headers as a list of tuples, `cache-control`
is set to `"max-age=0, private, must-revalidate"` by default.
Note: Use all lowercase for response headers.
* `status` - the response status
## Connection fields
* `assigns` - shared user data as a map
* `owner` - the Elixir process that owns the connection
* `halted` - the boolean status on whether the pipeline was halted
* `secret_key_base` - a secret key used to verify and encrypt cookies.
These features require manual field setup. Data must be kept in the
connection and never used directly. Always use `Plug.Crypto.KeyGenerator.generate/3`
to derive keys from it.
* `state` - the connection state
The connection state is used to track the connection lifecycle. It starts as
`:unset` but is changed to `:set` (via `resp/3`) or `:set_chunked`
(used only for `before_send` callbacks by `send_chunked/2`) or `:file`
(when invoked via `send_file/3`). Its final result is `:sent`, `:file`, `:chunked`
or `:upgraded` depending on the response model.
## Private fields
These fields are reserved for libraries/framework usage.
* `adapter` - holds the adapter information in a tuple
* `private` - shared library data as a map
## Deprecated fields
* `path_params` - the request path params, populated by routers such as `Plug.Router`.
Use `conn.params` instead.
* `req_cookies` - the decoded request cookies (without decrypting or verifying them).
Use `get_req_header/2` or `get_cookies/1` instead.
* `cookies`- the request cookies with the response cookies.
Use `get_cookies/1` instead.
* `resp_cookies`- the request cookies with the response cookies.
Use `get_resp_cookies/1` instead.
## Custom status codes
`Plug` allows status codes to be overridden or added and allow new codes not directly
specified by `Plug` or its adapters. The `:plug` application's Mix config can add or
override a status code.
For example, the config below overrides the default 404 reason phrase ("Not Found")
and adds a new 998 status code:
config :plug, :statuses, %{
404 => "Actually This Was Found",
998 => "Not An RFC Status Code"
}
Dependency-specific config changes are not automatically recompiled. Recompile `Plug`
for the changes to take place. The command below recompiles `Plug`:
mix deps.clean --build plug
A corresponding atom is inflected from each status code reason phrase. In many functions,
these atoms can stand in for the status code. For example, with the above configuration,
the following will work:
put_status(conn, :not_found) # 404
put_status(conn, :actually_this_was_found) # 404
put_status(conn, :not_an_rfc_status_code) # 998
The `:not_found` atom can still be used to set the 404 status even though the 404 status code
reason phrase was overwritten. The new atom `:actually_this_was_found`, inflected from the
reason phrase "Actually This Was Found", can also be used to set the 404 status code.
## Protocol Upgrades
`Plug.Conn.upgrade_adapter/3` provides basic support for protocol upgrades and facilitates
connection upgrades to protocols such as WebSockets. As the name suggests, this functionality
is adapter-dependent. Protocol upgrade functionality requires explicit coordination between
a `Plug` application and the underlying adapter.
`Plug` upgrade-related functionality only provides the possibility for the `Plug` application
to request protocol upgrades from the underlying adapter. See `upgrade_adapter/3` documentation.
"""
@type adapter :: {module, term}
@type assigns :: %{optional(atom) => any}
@type body :: iodata
@type req_cookies :: %{optional(binary) => binary}
@type cookies :: %{optional(binary) => term}
@type halted :: boolean
@type headers :: [{binary, binary}]
@type host :: binary
@type int_status :: non_neg_integer | nil
@type owner :: pid
@type method :: binary
@type query_param :: binary | %{optional(binary) => query_param} | [query_param]
@type query_params :: %{optional(binary) => query_param}
@type params :: %{optional(binary) => term}
@type port_number :: :inet.port_number()
@type query_string :: String.t()
@type resp_cookies :: %{optional(binary) => map()}
@type scheme :: :http | :https
@type secret_key_base :: binary | nil
@type segments :: [binary]
@type state :: :unset | :set | :set_chunked | :set_file | :file | :chunked | :sent | :upgraded
@type status :: atom | int_status
@type t :: %__MODULE__{
adapter: adapter,
assigns: assigns,
body_params: params | Unfetched.t(),
cookies: cookies | Unfetched.t(),
halted: halted,
host: host,
method: method,
owner: owner,
params: params | Unfetched.t(),
path_info: segments,
path_params: query_params,
port: :inet.port_number(),
private: assigns,
query_params: query_params | Unfetched.t(),
query_string: query_string,
remote_ip: :inet.ip_address(),
req_cookies: req_cookies | Unfetched.t(),
req_headers: headers,
request_path: binary,
resp_body: body | nil,
resp_cookies: resp_cookies,
resp_headers: headers,
scheme: scheme,
script_name: segments,
secret_key_base: secret_key_base,
state: state,
status: int_status
}
defstruct adapter: {Plug.MissingAdapter, nil},
assigns: %{},
body_params: %Unfetched{aspect: :body_params},
cookies: %Unfetched{aspect: :cookies},
halted: false,
host: "www.example.com",
method: "GET",
owner: nil,
params: %Unfetched{aspect: :params},
path_info: [],
path_params: %{},
port: 0,
private: %{},
query_params: %Unfetched{aspect: :query_params},
query_string: "",
remote_ip: nil,
req_cookies: %Unfetched{aspect: :cookies},
req_headers: [],
request_path: "",
resp_body: nil,
resp_cookies: %{},
resp_headers: [{"cache-control", "max-age=0, private, must-revalidate"}],
scheme: :http,
script_name: [],
secret_key_base: nil,
state: :unset,
status: nil
defmodule NotSentError do
defexception message: "a response was neither set nor sent from the connection"
@moduledoc """
Error raised when no response is sent in a request
"""
end
defmodule AlreadySentError do
defexception message: "the response was already sent"
@moduledoc """
Error raised when trying to modify or send an already sent response
"""
end
defmodule CookieOverflowError do
defexception message: "cookie exceeds maximum size of 4096 bytes"
@moduledoc """
Error raised when the cookie exceeds the maximum size of 4096 bytes.
"""
end
defmodule InvalidHeaderError do
defexception message: "header is invalid"
@moduledoc ~S"""
Error raised when trying to send a header that has errors, for example:
* the header key contains uppercase chars
* the header value contains newlines \n
"""
end
defmodule InvalidQueryError do
@moduledoc """
Raised when the request string is malformed, for example:
* the query has bad utf-8 encoding
* the query fails to www-form decode
"""
defexception message: "query string is invalid", plug_status: 400
end
alias Plug.Conn
@epoch {{1970, 1, 1}, {0, 0, 0}}
@already_sent {:plug_conn, :sent}
@unsent [:unset, :set, :set_chunked, :set_file]
@doc """
Assigns a value to a key in the connection.
The `assigns` storage is meant to be used to store values in the connection
so that other plugs in your plug pipeline can access them. The `assigns` storage
is a map.
## Examples
iex> conn.assigns[:hello]
nil
iex> conn = assign(conn, :hello, :world)
iex> conn.assigns[:hello]
:world
"""
@spec assign(t, atom, term) :: t
def assign(%Conn{assigns: assigns} = conn, key, value) when is_atom(key) do
%{conn | assigns: Map.put(assigns, key, value)}
end
@doc """
Assigns multiple values to keys in the connection.
Equivalent to multiple calls to `assign/3`.
## Examples
iex> conn.assigns[:hello]
nil
iex> conn = merge_assigns(conn, hello: :world)
iex> conn.assigns[:hello]
:world
"""
@spec merge_assigns(t, Enumerable.t()) :: t
def merge_assigns(%Conn{assigns: assigns} = conn, new) do
%{conn | assigns: Enum.into(new, assigns)}
end
@doc false
@deprecated "Call assign + Task.async instead"
def async_assign(%Conn{} = conn, key, fun) when is_atom(key) and is_function(fun, 0) do
assign(conn, key, Task.async(fun))
end
@doc false
@deprecated "Fetch the assign and call Task.await instead"
def await_assign(%Conn{} = conn, key, timeout \\ 5000) when is_atom(key) do
task = Map.fetch!(conn.assigns, key)
assign(conn, key, Task.await(task, timeout))
end
@doc """
Assigns a new **private** key and value in the connection.
This storage is meant to be used by libraries and frameworks to avoid writing
to the user storage (the `:assigns` field). It is recommended for
libraries/frameworks to prefix the keys with the library name.
For example, if a plug called `my_plug` needs to store a `:hello`
key, it would store it as `:my_plug_hello`:
iex> conn.private[:my_plug_hello]
nil
iex> conn = put_private(conn, :my_plug_hello, :world)
iex> conn.private[:my_plug_hello]
:world
"""
@spec put_private(t, atom, term) :: t
def put_private(%Conn{private: private} = conn, key, value) when is_atom(key) do
%{conn | private: Map.put(private, key, value)}
end
@doc """
Assigns multiple **private** keys and values in the connection.
Equivalent to multiple `put_private/3` calls.
## Examples
iex> conn.private[:my_plug_hello]
nil
iex> conn = merge_private(conn, my_plug_hello: :world)
iex> conn.private[:my_plug_hello]
:world
"""
@spec merge_private(t, Enumerable.t()) :: t
def merge_private(%Conn{private: private} = conn, new) do
%{conn | private: Enum.into(new, private)}
end
@doc """
Stores the given status code in the connection.
The status code can be `nil`, an integer, or an atom. The list of allowed
atoms is available in `Plug.Conn.Status`.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
## Examples
Plug.Conn.put_status(conn, :not_found)
Plug.Conn.put_status(conn, 200)
"""
@spec put_status(t, status) :: t
def put_status(%Conn{state: state}, _status) when state not in @unsent do
raise AlreadySentError
end
def put_status(%Conn{} = conn, nil), do: %{conn | status: nil}
def put_status(%Conn{} = conn, status), do: %{conn | status: Plug.Conn.Status.code(status)}
@doc """
Sends a response to the client.
It expects the connection state to be `:set`, otherwise raises an
`ArgumentError` for `:unset` connections or a `Plug.Conn.AlreadySentError` for
already `:sent`, `:chunked` or `:upgraded` connections.
At the end sets the connection state to `:sent`.
Note that this function does not halt the connection, so if
subsequent plugs try to send another response, it will error out.
Use `halt/1` after this function if you want to halt the plug pipeline.
## Examples
conn
|> Plug.Conn.resp(404, "Not found")
|> Plug.Conn.send_resp()
"""
@spec send_resp(t) :: t | no_return
def send_resp(conn)
def send_resp(%Conn{state: :unset}) do
raise ArgumentError, "cannot send a response that was not set"
end
def send_resp(%Conn{adapter: {adapter, payload}, state: :set, owner: owner} = conn) do
conn = run_before_send(conn, :set)
{:ok, body, payload} =
adapter.send_resp(payload, conn.status, conn.resp_headers, conn.resp_body)
send(owner, @already_sent)
%{conn | adapter: {adapter, payload}, resp_body: body, state: :sent}
end
def send_resp(%Conn{}) do
raise AlreadySentError
end
@doc """
Sends a file as the response body with the given `status`
and optionally starting at the given offset until the given length.
If available, the file is sent directly over the socket using
the operating system `sendfile` operation.
It expects a connection that has not been `:sent`, `:chunked` or `:upgraded` yet and sets its
state to `:file` afterwards. Otherwise raises `Plug.Conn.AlreadySentError`.
## Examples
Plug.Conn.send_file(conn, 200, "README.md")
"""
@spec send_file(t, status, filename :: binary, offset :: integer, length :: integer | :all) ::
t | no_return
def send_file(conn, status, file, offset \\ 0, length \\ :all)
def send_file(%Conn{state: state}, status, _file, _offset, _length)
when state not in @unsent do
_ = Plug.Conn.Status.code(status)
raise AlreadySentError
end
def send_file(
%Conn{adapter: {adapter, payload}, owner: owner} = conn,
status,
file,
offset,
length
)
when is_binary(file) do
if file =~ "\0" do
raise ArgumentError, "cannot send_file/5 with null byte"
end
conn =
run_before_send(%{conn | status: Plug.Conn.Status.code(status), resp_body: nil}, :set_file)
{:ok, body, payload} =
adapter.send_file(payload, conn.status, conn.resp_headers, file, offset, length)
send(owner, @already_sent)
%{conn | adapter: {adapter, payload}, state: :file, resp_body: body}
end
@doc """
Sends the response headers as a chunked response.
It expects a connection that has not been `:sent` or `:upgraded` yet and sets its
state to `:chunked` afterwards. Otherwise, raises `Plug.Conn.AlreadySentError`.
After `send_chunked/2` is called, chunks can be sent to the client via
the `chunk/2` function.
HTTP/2 does not support chunking and will instead stream the response without a
transfer encoding. When using HTTP/1.1, the Cowboy adapter will stream the response
instead of emitting chunks if the `content-length` header has been set before calling
`send_chunked/2`.
"""
@spec send_chunked(t, status) :: t | no_return
def send_chunked(%Conn{state: state}, status)
when state not in @unsent do
_ = Plug.Conn.Status.code(status)
raise AlreadySentError
end
def send_chunked(%Conn{adapter: {adapter, payload}, owner: owner} = conn, status) do
conn = %{conn | status: Plug.Conn.Status.code(status), resp_body: nil}
conn = run_before_send(conn, :set_chunked)
{:ok, body, payload} = adapter.send_chunked(payload, conn.status, conn.resp_headers)
send(owner, @already_sent)
%{conn | adapter: {adapter, payload}, state: :chunked, resp_body: body}
end
@doc """
Sends a chunk as part of a chunked response.
It expects a connection with state `:chunked` as set by
`send_chunked/2`. It returns `{:ok, conn}` in case of success,
otherwise `{:error, reason}`.
To stream data use `Enum.reduce_while/3` instead of `Enum.reduce/2`.
`Enum.reduce_while/3` allows aborting the execution if `chunk/2` fails to
deliver the chunk of data.
## Example
Enum.reduce_while(~w(each chunk as a word), conn, fn (chunk, conn) ->
case Plug.Conn.chunk(conn, chunk) do
{:ok, conn} ->
{:cont, conn}
{:error, :closed} ->
{:halt, conn}
end
end)
"""
@spec chunk(t, body) :: {:ok, t} | {:error, term} | no_return
def chunk(%Conn{adapter: {adapter, payload}, state: :chunked} = conn, chunk) do
if iodata_empty?(chunk) do
{:ok, conn}
else
case adapter.chunk(payload, chunk) do
:ok -> {:ok, conn}
{:ok, body, payload} -> {:ok, %{conn | resp_body: body, adapter: {adapter, payload}}}
{:error, _} = error -> error
end
end
end
def chunk(%Conn{}, chunk) when is_binary(chunk) or is_list(chunk) do
raise ArgumentError,
"chunk/2 expects a chunked response. Please ensure " <>
"you have called send_chunked/2 before you send a chunk"
end
defp iodata_empty?(""), do: true
defp iodata_empty?([]), do: true
defp iodata_empty?([head | tail]), do: iodata_empty?(head) and iodata_empty?(tail)
defp iodata_empty?(_), do: false
@doc """
Sends a response with the given status and body.
This is equivalent to setting the status and the body and then
calling `send_resp/1`.
Note that this function does not halt the connection, so if
subsequent plugs try to send another response, it will error out.
Use `halt/1` after this function if you want to halt the plug pipeline.
## Examples
Plug.Conn.send_resp(conn, 404, "Not found")
"""
@spec send_resp(t, status, body) :: t | no_return
def send_resp(%Conn{} = conn, status, body) do
conn |> resp(status, body) |> send_resp()
end
@doc """
Sets the response to the given `status` and `body`.
It sets the connection state to `:set` (if not already `:set`)
and raises `Plug.Conn.AlreadySentError` if it was already `:sent`, `:chunked` or `:upgraded`.
If you also want to send the response, use `send_resp/1` after this
or use `send_resp/3`.
The status can be an integer, an atom, or `nil`. See `Plug.Conn.Status`
for more information.
## Examples
Plug.Conn.resp(conn, 404, "Not found")
"""
@spec resp(t, status, body) :: t
def resp(%Conn{state: state}, status, _body)
when state not in @unsent do
_ = Plug.Conn.Status.code(status)
raise AlreadySentError
end
def resp(%Conn{}, _status, nil) do
raise ArgumentError, "response body cannot be set to nil"
end
def resp(%Conn{} = conn, status, body)
when is_binary(body) or is_list(body) do
%{conn | status: Plug.Conn.Status.code(status), resp_body: body, state: :set}
end
@doc """
Returns the request peer data if one is present.
"""
@spec get_peer_data(t) :: Plug.Conn.Adapter.peer_data()
def get_peer_data(%Conn{adapter: {adapter, payload}}) do
adapter.get_peer_data(payload)
end
@doc """
Returns the HTTP protocol and version.
## Examples
iex> get_http_protocol(conn)
:"HTTP/1.1"
"""
@spec get_http_protocol(t) :: Plug.Conn.Adapter.http_protocol()
def get_http_protocol(%Conn{adapter: {adapter, payload}}) do
adapter.get_http_protocol(payload)
end
@doc """
Returns the values of the request header specified by `key`.
## Examples
iex> get_req_header(conn, "accept")
["application/json"]
"""
@spec get_req_header(t, binary) :: [binary]
def get_req_header(%Conn{req_headers: headers}, key) when is_binary(key) do
for {^key, value} <- headers, do: value
end
@doc ~S"""
Prepends the list of headers to the connection request headers.
Similar to `put_req_header` this functions adds a new request header
(`key`) but rather than replacing the existing one it prepends another
header with the same `key`.
The "host" header will be overridden by `conn.host` and should not be set
with this method. Instead, do `%Plug.Conn{conn | host: value}`.
Because header keys are case-insensitive in both HTTP/1.1 and HTTP/2,
it is recommended for header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, requests with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped requests.
As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any
headers that aren't lowercase will raise a `Plug.Conn.InvalidHeaderError`.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
## Examples
Plug.Conn.prepend_req_headers(conn, [{"accept", "application/json"}])
"""
@spec prepend_req_headers(t, headers) :: t
def prepend_req_headers(conn, headers)
def prepend_req_headers(%Conn{state: state}, _headers) when state not in @unsent do
raise AlreadySentError
end
def prepend_req_headers(%Conn{adapter: adapter, req_headers: req_headers} = conn, headers)
when is_list(headers) do
for {key, _value} <- headers do
validate_req_header!(adapter, key)
end
%{conn | req_headers: headers ++ req_headers}
end
@doc """
Merges a series of request headers into the connection.
The "host" header will be overridden by `conn.host` and should not be set
with this method. Instead, do `%Plug.Conn{conn | host: value}`.
Because header keys are case-insensitive in both HTTP/1.1 and HTTP/2,
it is recommended for header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, requests with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped requests.
As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any
headers that aren't lowercase will raise a `Plug.Conn.InvalidHeaderError`.
## Example
Plug.Conn.merge_req_headers(conn, [{"accept", "text/plain"}, {"X-1337", "5P34K"}])
"""
@spec merge_req_headers(t, Enum.t()) :: t
def merge_req_headers(conn, headers)
def merge_req_headers(%Conn{state: state}, _headers) when state not in @unsent do
raise AlreadySentError
end
def merge_req_headers(conn, headers) when headers == %{} do
conn
end
def merge_req_headers(%Conn{req_headers: current, adapter: adapter} = conn, headers) do
headers =
Enum.reduce(headers, current, fn {key, value}, acc
when is_binary(key) and is_binary(value) ->
validate_req_header!(adapter, key)
List.keystore(acc, key, 0, {key, value})
end)
%{conn | req_headers: headers}
end
@doc """
Adds a new request header (`key`) if not present, otherwise replaces the
previous value of that header with `value`.
The "host" header will be overridden by `conn.host` and should not be set
with this method. Instead, do `%Plug.Conn{conn | host: value}`.
Because header keys are case-insensitive in both HTTP/1.1 and HTTP/2,
it is recommended for header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, requests with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped requests.
As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any
headers that aren't lowercase will raise a `Plug.Conn.InvalidHeaderError`.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
## Examples
Plug.Conn.put_req_header(conn, "accept", "application/json")
"""
@spec put_req_header(t, binary, binary) :: t
def put_req_header(conn, key, value)
def put_req_header(%Conn{state: state}, _key, _value) when state not in @unsent do
raise AlreadySentError
end
def put_req_header(%Conn{adapter: adapter, req_headers: headers} = conn, key, value)
when is_binary(key) and is_binary(value) do
validate_req_header!(adapter, key)
%{conn | req_headers: List.keystore(headers, key, 0, {key, value})}
end
@doc """
Deletes a request header if present.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
## Examples
Plug.Conn.delete_req_header(conn, "content-type")
"""
@spec delete_req_header(t, binary) :: t
def delete_req_header(conn, key)
def delete_req_header(%Conn{state: state}, _key) when state not in @unsent do
raise AlreadySentError
end
def delete_req_header(%Conn{req_headers: headers} = conn, key)
when is_binary(key) do
%{conn | req_headers: List.keydelete(headers, key, 0)}
end
@doc """
Updates a request header if present, otherwise it sets it to an initial
value.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
Only the first value of the header `key` is updated if present.
## Examples
Plug.Conn.update_req_header(
conn,
"accept",
"application/json; charset=utf-8",
&(&1 <> "; charset=utf-8")
)
"""
@spec update_req_header(t, binary, binary, (binary -> binary)) :: t
def update_req_header(conn, key, initial, fun)
def update_req_header(%Conn{state: state}, _key, _initial, _fun) when state not in @unsent do
raise AlreadySentError
end
def update_req_header(%Conn{} = conn, key, initial, fun)
when is_binary(key) and is_binary(initial) and is_function(fun, 1) do
case get_req_header(conn, key) do
[] -> put_req_header(conn, key, initial)
[current | _] -> put_req_header(conn, key, fun.(current))
end
end
@doc """
Returns the values of the response header specified by `key`.
## Examples
iex> conn = %{conn | resp_headers: [{"content-type", "text/plain"}]}
iex> get_resp_header(conn, "content-type")
["text/plain"]
"""
@spec get_resp_header(t, binary) :: [binary]
def get_resp_header(%Conn{resp_headers: headers}, key) when is_binary(key) do
for {^key, value} <- headers, do: value
end
@doc ~S"""
Adds a new response header (`key`) if not present, otherwise replaces the
previous value of that header with `value`.
Because header keys are case-insensitive in both HTTP/1.1 and HTTP/2,
it is recommended for header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, responses with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped responses.
As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any
headers that aren't lowercase will raise a `Plug.Conn.InvalidHeaderError`.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
Raises a `Plug.Conn.InvalidHeaderError` if the header value contains control
feed (`\r`) or newline (`\n`) characters.
## Examples
Plug.Conn.put_resp_header(conn, "content-type", "application/json")
"""
@spec put_resp_header(t, binary, binary) :: t
def put_resp_header(%Conn{state: state}, _key, _value) when state not in @unsent do
raise AlreadySentError
end
def put_resp_header(%Conn{adapter: adapter, resp_headers: headers} = conn, key, value)
when is_binary(key) and is_binary(value) do
validate_header_key_normalized_if_test!(adapter, key)
validate_header_key_value!(key, value)
%{conn | resp_headers: List.keystore(headers, key, 0, {key, value})}
end
@doc ~S"""
Prepends the list of headers to the connection response headers.
Similar to `put_resp_header` this functions adds a new response header
(`key`) but rather than replacing the existing one it prepends another header
with the same `key`.
It is recommended for header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, responses with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped responses.
As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any
headers that aren't lowercase will raise a `Plug.Conn.InvalidHeaderError`.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
Raises a `Plug.Conn.InvalidHeaderError` if the header value contains control
feed (`\r`) or newline (`\n`) characters.
## Examples
Plug.Conn.prepend_resp_headers(conn, [{"content-type", "application/json"}])
"""
@spec prepend_resp_headers(t, headers) :: t
def prepend_resp_headers(conn, headers)
def prepend_resp_headers(%Conn{state: state}, _headers) when state not in @unsent do
raise AlreadySentError
end
def prepend_resp_headers(%Conn{adapter: adapter, resp_headers: resp_headers} = conn, headers)
when is_list(headers) do
for {key, value} <- headers do
validate_header_key_normalized_if_test!(adapter, key)
validate_header_key_value!(key, value)
end
%{conn | resp_headers: headers ++ resp_headers}
end
@doc """
Merges a series of response headers into the connection.
It is recommended for header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, responses with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped responses.
As a convenience, when using the `Plug.Adapters.Conn.Test` adapter, any
headers that aren't lowercase will raise a `Plug.Conn.InvalidHeaderError`.
## Example
Plug.Conn.merge_resp_headers(conn, [{"content-type", "text/plain"}, {"X-1337", "5P34K"}])
"""
@spec merge_resp_headers(t, Enum.t()) :: t
def merge_resp_headers(conn, headers)
def merge_resp_headers(%Conn{state: state}, _headers) when state not in @unsent do
raise AlreadySentError
end
def merge_resp_headers(conn, headers) when headers == %{} do
conn
end
def merge_resp_headers(%Conn{resp_headers: current, adapter: adapter} = conn, headers) do
headers =
Enum.reduce(headers, current, fn {key, value}, acc
when is_binary(key) and is_binary(value) ->
validate_header_key_normalized_if_test!(adapter, key)
validate_header_key_value!(key, value)
List.keystore(acc, key, 0, {key, value})
end)
%{conn | resp_headers: headers}
end
@doc """
Deletes a response header if present.
Raises a `Plug.Conn.AlreadySentError` if the connection has already been
`:sent`, `:chunked` or `:upgraded`.
## Examples
Plug.Conn.delete_resp_header(conn, "content-type")
"""
@spec delete_resp_header(t, binary) :: t
def delete_resp_header(%Conn{state: state}, _key) when state not in @unsent do
raise AlreadySentError
end
def delete_resp_header(%Conn{resp_headers: headers} = conn, key)
when is_binary(key) do
%{conn | resp_headers: List.keydelete(headers, key, 0)}
end
@doc """
Updates a response header if present, otherwise it sets it to an initial
value.