File: Req.hs

package info (click to toggle)
haskell-req 3.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 204 kB
  • sloc: haskell: 1,913; makefile: 3
file content (2051 lines) | stat: -rw-r--r-- 71,036 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE TemplateHaskellQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}

-- |
-- Module      :  Network.HTTP.Req
-- Copyright   :  © 2016–present Mark Karpov
-- License     :  BSD 3 clause
--
-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>
-- Stability   :  experimental
-- Portability :  portable
--
-- The documentation below is structured in such a way that the most
-- important information is presented first: you learn how to do HTTP
-- requests, how to embed them in the monad you have, and then it gives you
-- details about less-common things you may want to know about. The
-- documentation is written with sufficient coverage of details and
-- examples, and it's designed to be a complete tutorial on its own.
--
-- === About the library
--
-- Req is an HTTP client library that attempts to be easy-to-use, type-safe,
-- and expandable.
--
-- “Easy-to-use” means that the library is designed to be beginner-friendly
-- so it's simple to add to your monad stack, intuitive to work with,
-- well-documented, and does not get in your way. Doing HTTP requests is a
-- common task and a Haskell library for this should be approachable and
-- clear to beginners, thus certain compromises were made. For example, one
-- cannot currently modify 'L.ManagerSettings' of the default manager
-- because the library always uses the same implicit global manager for
-- simplicity and maximal connection sharing. There is a way to use your own
-- manager with different settings, but it requires more typing.
--
-- “Type-safe” means that the library tries to eliminate certain classes of
-- errors. For example, we have correct-by-construction URLs; it is
-- guaranteed that the user does not send the request body when using
-- methods like GET or OPTIONS, and the amount of implicit assumptions is
-- minimized by making the user specify their intentions in an explicit
-- form. For example, it's not possible to avoid specifying the body or the
-- method of a request. Authentication methods that assume HTTPS force the
-- user to use HTTPS at the type level.
--
-- “Expandable” refers to the ability to create new components without
-- having to resort to hacking. For example, it's possible to define your
-- own HTTP methods, create new ways to construct the body of a request,
-- create new authorization options, perform a request in a different way,
-- and create your own methods to parse a response.
--
-- === Using with other libraries
--
--     * You won't need the low-level interface of @http-client@ most of the
--       time, but when you do, it's better to do a qualified import,
--       because @http-client@ has naming conflicts with @req@.
--     * For streaming of large request bodies see the companion package
--       @req-conduit@: <https://hackage.haskell.org/package/req-conduit>.
--
-- === Lightweight, no risk solution
--
-- The library uses the following mature packages under the hood to
-- guarantee you the best experience:
--
--     * <https://hackage.haskell.org/package/http-client>—low level HTTP
--       client used everywhere in Haskell.
--     * <https://hackage.haskell.org/package/http-client-tls>—TLS (HTTPS)
--       support for @http-client@.
--
-- It's important to note that since we leverage well-known libraries that
-- the whole Haskell ecosystem uses, there is no risk in using @req@. The
-- machinery for performing requests is the same as with @http-conduit@ and
-- @wreq@. The only difference is the API.
module Network.HTTP.Req
  ( -- * Making a request
    -- $making-a-request
    req,
    reqBr,
    reqCb,
    req',
    withReqManager,

    -- * Embedding requests in your monad
    -- $embedding-requests
    MonadHttp (..),
    HttpConfig (..),
    defaultHttpConfig,
    Req,
    runReq,

    -- * Request

    -- ** Method
    -- $method
    GET (..),
    POST (..),
    HEAD (..),
    PUT (..),
    DELETE (..),
    TRACE (..),
    CONNECT (..),
    OPTIONS (..),
    PATCH (..),
    HttpMethod (..),

    -- ** URL
    -- $url
    Url,
    http,
    https,
    (/~),
    (/:),
    useHttpURI,
    useHttpsURI,
    useURI,
    urlQ,
    renderUrl,

    -- ** Body
    -- $body
    NoReqBody (..),
    ReqBodyJson (..),
    ReqBodyFile (..),
    ReqBodyBs (..),
    ReqBodyLbs (..),
    ReqBodyUrlEnc (..),
    FormUrlEncodedParam,
    ReqBodyMultipart,
    reqBodyMultipart,
    HttpBody (..),
    ProvidesBody,
    HttpBodyAllowed,

    -- ** Optional parameters
    -- $optional-parameters
    Option,

    -- *** Query parameters
    -- $query-parameters
    (=:),
    queryFlag,
    formToQuery,
    QueryParam (..),

    -- *** Headers
    header,
    attachHeader,
    headerRedacted,

    -- *** Cookies
    -- $cookies
    cookieJar,

    -- *** Authentication
    -- $authentication
    basicAuth,
    basicAuthUnsafe,
    basicProxyAuth,
    oAuth1,
    oAuth2Bearer,
    oAuth2Token,
    customAuth,

    -- *** Other
    port,
    decompress,
    responseTimeout,
    httpVersion,

    -- * Response

    -- ** Response interpretations
    IgnoreResponse,
    ignoreResponse,
    JsonResponse,
    jsonResponse,
    BsResponse,
    bsResponse,
    LbsResponse,
    lbsResponse,

    -- ** Inspecting a response
    responseBody,
    responseStatusCode,
    responseStatusMessage,
    responseHeader,
    responseCookieJar,

    -- ** Defining your own interpretation
    -- $new-response-interpretation
    HttpResponse (..),

    -- * Other
    HttpException (..),
    isStatusCodeException,
    CanHaveBody (..),
    Scheme (..),
  )
where

import Blaze.ByteString.Builder qualified as BB
import Control.Applicative
import Control.Arrow (first, second)
import Control.Exception hiding (Handler (..), TypeError)
import Control.Monad (guard, void, (>=>))
import Control.Monad.Base
import Control.Monad.Catch (Handler (..), MonadCatch, MonadMask, MonadThrow)
import Control.Monad.IO.Class
import Control.Monad.IO.Unlift
import Control.Monad.Reader (ReaderT (ReaderT), ask, lift, runReaderT)
import Control.Monad.Trans.Accum (AccumT)
import Control.Monad.Trans.Cont (ContT)
import Control.Monad.Trans.Control
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Identity (IdentityT)
import Control.Monad.Trans.Maybe (MaybeT)
import Control.Monad.Trans.RWS.CPS qualified as RWS.CPS
import Control.Monad.Trans.RWS.Lazy qualified as RWS.Lazy
import Control.Monad.Trans.RWS.Strict qualified as RWS.Strict
import Control.Monad.Trans.Select (SelectT)
import Control.Monad.Trans.State.Lazy qualified as State.Lazy
import Control.Monad.Trans.State.Strict qualified as State.Strict
import Control.Monad.Trans.Writer.CPS qualified as Writer.CPS
import Control.Monad.Trans.Writer.Lazy qualified as Writer.Lazy
import Control.Monad.Trans.Writer.Strict qualified as Writer.Strict
import Control.Retry
import Data.Aeson (FromJSON (..), ToJSON (..))
import Data.Aeson qualified as A
import Data.ByteString (ByteString)
import Data.ByteString qualified as B
import Data.ByteString.Lazy qualified as BL
import Data.CaseInsensitive qualified as CI
import Data.Data (Data)
import Data.Function (on)
import Data.IORef
import Data.Kind (Constraint, Type)
import Data.List (foldl', nubBy)
import Data.List.NonEmpty (NonEmpty (..))
import Data.List.NonEmpty qualified as NE
import Data.Maybe (fromMaybe)
import Data.Proxy
import Data.Semigroup (Endo (..))
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as T
import Data.Typeable (Typeable, cast)
import GHC.Generics
import GHC.TypeLits
import Language.Haskell.TH qualified as TH
import Language.Haskell.TH.Quote qualified as TH
import Language.Haskell.TH.Syntax qualified as TH
import Network.Connection qualified as NC
import Network.HTTP.Client qualified as L
import Network.HTTP.Client.Internal qualified as LI
import Network.HTTP.Client.MultipartFormData qualified as LM
import Network.HTTP.Client.TLS qualified as L
import Network.HTTP.Types qualified as Y
import System.IO.Unsafe (unsafePerformIO)
import Text.URI (URI)
import Text.URI qualified as URI
import Text.URI.QQ qualified as QQ
import Web.Authenticate.OAuth qualified as OAuth
import Web.FormUrlEncoded (FromForm (..), ToForm (..))
import Web.FormUrlEncoded qualified as Form
import Web.HttpApiData (ToHttpApiData (..))

----------------------------------------------------------------------------
-- Making a request

-- $making-a-request
--
-- To make an HTTP request you normally need only one function: 'req'.

-- | Make an HTTP request. The function takes 5 arguments, 4 of which
-- specify required parameters and the final 'Option' argument is a
-- collection of optional parameters.
--
-- Let's go through all the arguments first: @req method url body response
-- options@.
--
-- @method@ is an HTTP method such as 'GET' or 'POST'. The documentation has
-- a dedicated section about HTTP methods below.
--
-- @url@ is a 'Url' that describes location of resource you want to interact
-- with.
--
-- @body@ is a body option such as 'NoReqBody' or 'ReqBodyJson'. The
-- tutorial has a section about HTTP bodies, but usage is very
-- straightforward and should be clear from the examples.
--
-- @response@ is a type hint how to make and interpret response of an HTTP
-- request. Out-of-the-box it can be the following:
--
--     * 'ignoreResponse'
--     * 'jsonResponse'
--     * 'bsResponse' (to get a strict 'ByteString')
--     * 'lbsResponse' (to get a lazy 'BL.ByteString')
--
-- Finally, @options@ is a 'Monoid' that holds a composite 'Option' for all
-- other optional settings like query parameters, headers, non-standard port
-- number, etc. There are quite a few things you can put there, see the
-- corresponding section in the documentation. If you don't need anything at
-- all, pass 'mempty'.
--
-- __Note__ that if you use 'req' to do all your requests, connection
-- sharing and reuse is done for you automatically.
--
-- See the examples below to get on the speed quickly.
--
-- ==== __Examples__
--
-- First, this is a piece of boilerplate that should be in place before you
-- try the examples:
--
-- > {-# LANGUAGE DeriveGeneric     #-}
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > module Main (main) where
-- >
-- > import Control.Monad
-- > import Control.Monad.IO.Class
-- > import Data.Aeson
-- > import Data.Maybe (fromJust)
-- > import Data.Monoid ((<>))
-- > import Data.Text (Text)
-- > import GHC.Generics
-- > import Network.HTTP.Req
-- > import qualified Data.ByteString.Char8 as B
-- > import qualified Text.URI as URI
--
-- We will be making requests against the <https://httpbin.org> service.
--
-- Make a GET request, grab 5 random bytes:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- >   let n :: Int
-- >       n = 5
-- >   bs <- req GET (https "httpbin.org" /: "bytes" /~ n) NoReqBody bsResponse mempty
-- >   liftIO $ B.putStrLn (responseBody bs)
--
-- The same, but now we use a query parameter named @\"seed\"@ to control
-- seed of the generator:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- >   let n, seed :: Int
-- >       n    = 5
-- >       seed = 100
-- >   bs <- req GET (https "httpbin.org" /: "bytes" /~ n) NoReqBody bsResponse $
-- >     "seed" =: seed
-- >   liftIO $ B.putStrLn (responseBody bs)
--
-- POST JSON data and get some info about the POST request:
--
-- > data MyData = MyData
-- >   { size  :: Int
-- >   , color :: Text
-- >   } deriving (Show, Generic)
-- >
-- > instance ToJSON MyData
-- > instance FromJSON MyData
-- >
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- >   let myData = MyData
-- >         { size  = 6
-- >         , color = "Green" }
-- >   v <- req POST (https "httpbin.org" /: "post") (ReqBodyJson myData) jsonResponse mempty
-- >   liftIO $ print (responseBody v :: Value)
--
-- Sending URL-encoded body:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- >   let params =
-- >         "foo" =: ("bar" :: Text) <>
-- >         queryFlag "baz"
-- >   response <- req POST (https "httpbin.org" /: "post") (ReqBodyUrlEnc params) jsonResponse mempty
-- >   liftIO $ print (responseBody response :: Value)
--
-- Using various optional parameters and URL that is not known in advance:
--
-- > main :: IO ()
-- > main = runReq defaultHttpConfig $ do
-- >   -- This is an example of what to do when URL is given dynamically. Of
-- >   -- course in a real application you may not want to use 'fromJust'.
-- >   uri <- URI.mkURI "https://httpbin.org/get?foo=bar"
-- >   let (url, options) = fromJust (useHttpsURI uri)
-- >   response <- req GET url NoReqBody jsonResponse $
-- >     "from" =: (15 :: Int)           <>
-- >     "to"   =: (67 :: Int)           <>
-- >     basicAuth "username" "password" <>
-- >     options                         <> -- contains the ?foo=bar part
-- >     port 443 -- here you can put any port of course
-- >   liftIO $ print (responseBody response :: Value)
req ::
  ( MonadHttp m,
    HttpMethod method,
    HttpBody body,
    HttpResponse response,
    HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
  ) =>
  -- | HTTP method
  method ->
  -- | 'Url'—location of resource
  Url scheme ->
  -- | Body of the request
  body ->
  -- | A hint how to interpret response
  Proxy response ->
  -- | Collection of optional parameters
  Option scheme ->
  -- | Response
  m response
req method url body responseProxy options =
  reqCb method url body responseProxy options pure

-- | A version of 'req' that does not use one of the predefined instances of
-- 'HttpResponse' but instead allows the user to consume @'L.Response'
-- 'L.BodyReader'@ manually, in a custom way.
--
-- @since 1.0.0
reqBr ::
  ( MonadHttp m,
    HttpMethod method,
    HttpBody body,
    HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
  ) =>
  -- | HTTP method
  method ->
  -- | 'Url'—location of resource
  Url scheme ->
  -- | Body of the request
  body ->
  -- | Collection of optional parameters
  Option scheme ->
  -- | How to consume response
  (L.Response L.BodyReader -> IO a) ->
  -- | Result
  m a
reqBr method url body options consume =
  req' method url body options (reqHandler consume)

-- | A version of 'req' that takes a callback to modify the 'L.Request', but
-- otherwise performs the request identically.
--
-- @since 3.7.0
reqCb ::
  ( MonadHttp m,
    HttpMethod method,
    HttpBody body,
    HttpResponse response,
    HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
  ) =>
  -- | HTTP method
  method ->
  -- | 'Url'—location of resource
  Url scheme ->
  -- | Body of the request
  body ->
  -- | A hint how to interpret response
  Proxy response ->
  -- | Collection of optional parameters
  Option scheme ->
  -- | Callback to modify the request
  (L.Request -> m L.Request) ->
  -- | Response
  m response
reqCb method url body responseProxy options adjustRequest =
  req' method url body (options <> extraOptions) $ \request manager -> do
    request' <- adjustRequest request
    reqHandler getHttpResponse request' manager
  where
    extraOptions =
      case acceptHeader responseProxy of
        Nothing -> mempty
        Just accept -> header "Accept" accept

-- | The default handler function that the higher-level request functions
-- pass to 'req''. Internal function.
--
-- @since 3.7.0
reqHandler ::
  (MonadHttp m) =>
  -- | How to get final result from a 'L.Response'
  (L.Response L.BodyReader -> IO b) ->
  -- | 'L.Request' to perform
  L.Request ->
  -- | 'L.Manager' to use
  L.Manager ->
  m b
reqHandler consume request manager = do
  HttpConfig {..} <- getHttpConfig
  let wrapVanilla = handle (throwIO . VanillaHttpException)
      wrapExc = handle (throwIO . LI.toHttpException request)
      withRRef =
        bracket
          (newIORef Nothing)
          (readIORef >=> mapM_ L.responseClose)
  (liftIO . try . wrapVanilla . wrapExc)
    ( withRRef $ \rref -> do
        let openResponse = mask_ $ do
              r <- readIORef rref
              mapM_ L.responseClose r
              r' <- L.responseOpen request manager
              writeIORef rref (Just r')
              return r'
            exceptionRetryPolicies =
              skipAsyncExceptions
                ++ [ \retryStatus -> Handler $ \e ->
                       return $ httpConfigRetryJudgeException retryStatus e
                   ]
        r <-
          retrying
            httpConfigRetryPolicy
            (\retryStatus r -> return $ httpConfigRetryJudge retryStatus r)
            ( const
                ( recovering
                    httpConfigRetryPolicy
                    exceptionRetryPolicies
                    (const openResponse)
                )
            )
        (preview, r') <- grabPreview httpConfigBodyPreviewLength r
        mapM_ LI.throwHttp (httpConfigCheckResponse request r' preview)
        consume r'
    )
    >>= either handleHttpException return

-- | Mostly like 'req' with respect to its arguments, but accepts a callback
-- that allows to perform a request in arbitrary fashion.
--
-- This function /does not/ perform handling\/wrapping exceptions, checking
-- response (with 'httpConfigCheckResponse'), and retrying. It only prepares
-- 'L.Request' and allows you to use it.
--
-- @since 0.3.0
req' ::
  forall m method body scheme a.
  ( MonadHttp m,
    HttpMethod method,
    HttpBody body,
    HttpBodyAllowed (AllowsBody method) (ProvidesBody body)
  ) =>
  -- | HTTP method
  method ->
  -- | 'Url'—location of resource
  Url scheme ->
  -- | Body of the request
  body ->
  -- | Collection of optional parameters
  Option scheme ->
  -- | How to perform request
  (L.Request -> L.Manager -> m a) ->
  -- | Result
  m a
req' method url body options m = do
  config <- getHttpConfig
  let -- NOTE First appearance of any given header wins. This allows to
      -- “overwrite” headers when we construct a request by cons-ing.
      nubHeaders = Endo $ \x ->
        x {L.requestHeaders = nubBy ((==) `on` fst) (L.requestHeaders x)}
      request' =
        flip appEndo L.defaultRequest $
          -- NOTE The order of 'mappend's matters, here method is overwritten
          -- first and 'options' take effect last. In particular, this means
          -- that 'options' can overwrite things set by other request
          -- components, which is useful for setting port number,
          -- "Content-Type" header, etc.
          nubHeaders
            <> getRequestMod options
            <> getRequestMod config
            <> getRequestMod (Tagged body :: Tagged "body" body)
            <> getRequestMod url
            <> getRequestMod (Tagged method :: Tagged "method" method)
  request <- finalizeRequest options request'
  withReqManager (m request)

-- | Perform an action using the global implicit 'L.Manager' that the rest
-- of the library uses. This allows to reuse connections that the
-- 'L.Manager' controls.
withReqManager :: (MonadIO m) => (L.Manager -> m a) -> m a
withReqManager m = liftIO (readIORef globalManager) >>= m

-- | The global 'L.Manager' that 'req' uses. Here we just go with the
-- default settings, so users don't need to deal with this manager stuff at
-- all, but when we create a request, instance 'HttpConfig' can affect the
-- default settings via 'getHttpConfig'.
--
-- A note about safety, in case 'unsafePerformIO' looks suspicious to you.
-- The value of 'globalManager' is named and lives on top level. This means
-- it will be shared, i.e. computed only once on the first use of the
-- manager. From that moment on the 'IORef' will be just reused—exactly the
-- behavior we want here in order to maximize connection sharing. GHC could
-- spoil the plan by inlining the definition, hence the @NOINLINE@ pragma.
globalManager :: IORef L.Manager
globalManager = unsafePerformIO $ do
  context <- NC.initConnectionContext
  let settings =
        L.mkManagerSettingsContext
          (Just context)
          (NC.TLSSettingsSimple False False False)
          Nothing
  manager <- L.newManager settings
  newIORef manager
{-# NOINLINE globalManager #-}

----------------------------------------------------------------------------
-- Embedding requests in your monad

-- $embedding-requests
--
-- To use 'req' in your monad, all you need to do is to make the monad an
-- instance of the 'MonadHttp' type class.
--
-- When writing a library, keep your API polymorphic in terms of
-- 'MonadHttp', only define instance of 'MonadHttp' in final application.
-- Another option is to use a @newtype@-wrapped monad stack and define
-- 'MonadHttp' for it. As of the version /0.4.0/, the 'Req' monad that
-- follows this strategy is provided out-of-the-box (see below).

-- | A type class for monads that support performing HTTP requests.
-- Typically, you only need to define the 'handleHttpException' method
-- unless you want to tweak 'HttpConfig'.
class (MonadIO m) => MonadHttp m where
  -- | This method describes how to deal with 'HttpException' that was
  -- caught by the library. One option is to re-throw it if you are OK with
  -- exceptions, but if you prefer working with something like
  -- 'Control.Monad.Except.MonadError', this is the right place to pass it to
  -- 'Control.Monad.Except.throwError'.
  handleHttpException :: HttpException -> m a

  -- | Return the 'HttpConfig' to be used when performing HTTP requests.
  -- Default implementation returns its 'def' value, which is described in
  -- the documentation for the type. Common usage pattern with manually
  -- defined 'getHttpConfig' is to return some hard-coded value, or a value
  -- extracted from 'Control.Monad.Reader.MonadReader' if a more flexible
  -- approach to configuration is desirable.
  getHttpConfig :: m HttpConfig
  getHttpConfig = return defaultHttpConfig

-- | 'HttpConfig' contains settings to be used when making HTTP requests.
data HttpConfig = HttpConfig
  { -- | Proxy to use. By default values of @HTTP_PROXY@ and @HTTPS_PROXY@
    -- environment variables are respected, this setting overwrites them.
    -- Default value: 'Nothing'.
    httpConfigProxy :: Maybe L.Proxy,
    -- | How many redirects to follow when getting a resource. Default
    -- value: 10.
    httpConfigRedirectCount :: Int,
    -- | Alternative 'L.Manager' to use. 'Nothing' (default value) means
    -- that the default implicit manager will be used (that's what you want
    -- in 99% of cases).
    httpConfigAltManager :: Maybe L.Manager,
    -- | Function to check the response immediately after receiving the
    -- status and headers, before streaming of response body. The third
    -- argument is the beginning of response body (typically first 1024
    -- bytes). This is used for throwing exceptions on non-success status
    -- codes by default (set to @\\_ _ _ -> Nothing@ if this behavior is not
    -- desirable).
    --
    -- When the value this function returns is 'Nothing', nothing will
    -- happen. When it there is 'L.HttpExceptionContent' inside 'Just', it
    -- will be thrown.
    --
    -- Throwing is better then just returning a request with non-2xx status
    -- code because in that case something is wrong and we need a way to
    -- short-cut execution (also remember that Req retries automatically on
    -- request timeouts and such, so when your request fails, it's certainly
    -- something exceptional). The thrown exception is caught by the library
    -- though and is available in 'handleHttpException'.
    --
    -- __Note__: signature of this function was changed in the version
    -- /1.0.0/.
    --
    -- @since 0.3.0
    httpConfigCheckResponse ::
      forall b.
      L.Request ->
      L.Response b ->
      ByteString ->
      Maybe L.HttpExceptionContent,
    -- | The retry policy to use for request retrying. By default 'def' is
    -- used (see 'RetryPolicyM').
    --
    -- __Note__: signature of this function was changed to disallow 'IO' in
    -- version /1.0.0/ and then changed back to its current form in /3.1.0/.
    --
    -- @since 0.3.0
    httpConfigRetryPolicy :: RetryPolicyM IO,
    -- | The function is used to decide whether to retry a request. 'True'
    -- means that the request should be retried.
    --
    -- __Note__: signature of this function was changed in the version
    -- /1.0.0/.
    --
    -- @since 0.3.0
    httpConfigRetryJudge :: forall b. RetryStatus -> L.Response b -> Bool,
    -- | Similar to 'httpConfigRetryJudge', but is used to decide when to
    -- retry requests that resulted in an exception. By default it retries
    -- on response timeout and connection timeout (changed in version
    -- /3.8.0/).
    --
    -- @since 3.4.0
    httpConfigRetryJudgeException :: RetryStatus -> SomeException -> Bool,
    -- | Max length of preview fragment of response body.
    --
    -- @since 3.6.0
    httpConfigBodyPreviewLength :: forall a. (Num a) => a
  }
  deriving (Typeable)

-- | The default value of 'HttpConfig'.
--
-- @since 2.0.0
defaultHttpConfig :: HttpConfig
defaultHttpConfig =
  HttpConfig
    { httpConfigProxy = Nothing,
      httpConfigRedirectCount = 10,
      httpConfigAltManager = Nothing,
      httpConfigCheckResponse = \_ response preview ->
        let scode = statusCode response
         in if 200 <= scode && scode < 300
              then Nothing
              else Just (L.StatusCodeException (void response) preview),
      httpConfigRetryPolicy = retryPolicyDefault,
      httpConfigRetryJudge = \_ response ->
        statusCode response
          `elem` [ 408, -- Request timeout
                   504, -- Gateway timeout
                   524, -- A timeout occurred
                   598, -- (Informal convention) Network read timeout error
                   599 -- (Informal convention) Network connect timeout error
                 ],
      httpConfigRetryJudgeException = \_ e ->
        case fromException e of
          Just (L.HttpExceptionRequest _ c) ->
            case c of
              L.ResponseTimeout -> True
              L.ConnectionTimeout -> True
              _ -> False
          _ -> False,
      httpConfigBodyPreviewLength = 1024
    }
  where
    statusCode = Y.statusCode . L.responseStatus

instance RequestComponent HttpConfig where
  getRequestMod HttpConfig {..} = Endo $ \x ->
    x
      { L.proxy = httpConfigProxy,
        L.redirectCount = httpConfigRedirectCount,
        LI.requestManagerOverride = httpConfigAltManager
      }

-- | A monad that allows us to run 'req' in any 'IO'-enabled monad without
-- having to define new instances.
--
-- @since 0.4.0
newtype Req a = Req (ReaderT HttpConfig IO a)
  deriving
    ( Functor,
      Applicative,
      Monad,
      MonadIO,
      MonadUnliftIO
    )

-- | @since 3.7.0
deriving instance MonadThrow Req

-- | @since 3.7.0
deriving instance MonadCatch Req

-- | @since 3.7.0
deriving instance MonadMask Req

instance MonadBase IO Req where
  liftBase = liftIO

instance MonadBaseControl IO Req where
  type StM Req a = a
  liftBaseWith f = Req . ReaderT $ \r -> f (runReq r)
  {-# INLINEABLE liftBaseWith #-}
  restoreM = Req . ReaderT . const . return
  {-# INLINEABLE restoreM #-}

instance MonadHttp Req where
  handleHttpException = Req . lift . throwIO
  getHttpConfig = Req ask

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (AccumT w m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (ContT r m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (ExceptT e m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (IdentityT m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (MaybeT m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (ReaderT r m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.CPS.RWST r w s m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.Lazy.RWST r w s m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (RWS.Strict.RWST r w s m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (SelectT r m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (State.Lazy.StateT s m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m) => MonadHttp (State.Strict.StateT s m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.CPS.WriterT w m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.Lazy.WriterT w m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | @since 3.10.0
instance (MonadHttp m, Monoid w) => MonadHttp (Writer.Strict.WriterT w m) where
  handleHttpException = lift . handleHttpException
  getHttpConfig = lift getHttpConfig

-- | Run a computation in the 'Req' monad with the given 'HttpConfig'. In
-- the case of an exceptional situation an 'HttpException' will be thrown.
--
-- @since 0.4.0
runReq ::
  (MonadIO m) =>
  -- | 'HttpConfig' to use
  HttpConfig ->
  -- | Computation to run
  Req a ->
  m a
runReq config (Req m) = liftIO (runReaderT m config)

----------------------------------------------------------------------------
-- Request—Method

-- $method
--
-- The package supports all methods as defined by RFC 2616, and 'PATCH'
-- which is defined by RFC 5789—that should be enough to talk to RESTful
-- APIs. In some cases, however, you may want to add more methods (e.g. you
-- work with WebDAV <https://en.wikipedia.org/wiki/WebDAV>); no need to
-- compromise on type safety and hack, it only takes a couple of seconds to
-- define a new method that will works seamlessly, see 'HttpMethod'.

-- | 'GET' method.
data GET = GET

instance HttpMethod GET where
  type AllowsBody GET = 'NoBody
  httpMethodName Proxy = Y.methodGet

-- | 'POST' method.
data POST = POST

instance HttpMethod POST where
  type AllowsBody POST = 'CanHaveBody
  httpMethodName Proxy = Y.methodPost

-- | 'HEAD' method.
data HEAD = HEAD

instance HttpMethod HEAD where
  type AllowsBody HEAD = 'NoBody
  httpMethodName Proxy = Y.methodHead

-- | 'PUT' method.
data PUT = PUT

instance HttpMethod PUT where
  type AllowsBody PUT = 'CanHaveBody
  httpMethodName Proxy = Y.methodPut

-- | 'DELETE' method. RFC 7231 allows a payload in DELETE but without
-- semantics.
--
-- __Note__: before version /3.4.0/ this method did not allow request
-- bodies.
data DELETE = DELETE

instance HttpMethod DELETE where
  type AllowsBody DELETE = 'CanHaveBody
  httpMethodName Proxy = Y.methodDelete

-- | 'TRACE' method.
data TRACE = TRACE

instance HttpMethod TRACE where
  type AllowsBody TRACE = 'CanHaveBody
  httpMethodName Proxy = Y.methodTrace

-- | 'CONNECT' method.
data CONNECT = CONNECT

instance HttpMethod CONNECT where
  type AllowsBody CONNECT = 'CanHaveBody
  httpMethodName Proxy = Y.methodConnect

-- | 'OPTIONS' method.
data OPTIONS = OPTIONS

instance HttpMethod OPTIONS where
  type AllowsBody OPTIONS = 'NoBody
  httpMethodName Proxy = Y.methodOptions

-- | 'PATCH' method.
data PATCH = PATCH

instance HttpMethod PATCH where
  type AllowsBody PATCH = 'CanHaveBody
  httpMethodName Proxy = Y.methodPatch

-- | A type class for types that can be used as an HTTP method. To define a
-- non-standard method, follow this example that defines @COPY@:
--
-- > data COPY = COPY
-- >
-- > instance HttpMethod COPY where
-- >   type AllowsBody COPY = 'CanHaveBody
-- >   httpMethodName Proxy = "COPY"
class HttpMethod a where
  -- | Type function 'AllowsBody' returns a type of kind 'CanHaveBody' which
  -- tells the rest of the library whether the method can have body or not.
  -- We use the special type 'CanHaveBody' lifted to the kind level instead
  -- of 'Bool' to get more user-friendly compiler messages.
  type AllowsBody a :: CanHaveBody

  -- | Return name of the method as a 'ByteString'.
  httpMethodName :: Proxy a -> ByteString

instance (HttpMethod method) => RequestComponent (Tagged "method" method) where
  getRequestMod _ = Endo $ \x ->
    x {L.method = httpMethodName (Proxy :: Proxy method)}

----------------------------------------------------------------------------
-- Request—URL

-- $url
--
-- We use 'Url's which are correct by construction, see 'Url'. To build a
-- 'Url' from a 'URI', use 'useHttpURI', 'useHttpsURI', or generic 'useURI'.

-- | Request's 'Url'. Start constructing your 'Url' with 'http' or 'https'
-- specifying the scheme and host at the same time. Then use the @('/~')@
-- and @('/:')@ operators to grow the path one piece at a time. Every single
-- piece of path will be url(percent)-encoded, so using @('/~')@ and
-- @('/:')@ is the only way to have forward slashes between path segments.
-- This approach makes working with dynamic path segments easy and safe. See
-- examples below how to represent various 'Url's (make sure the
-- @OverloadedStrings@ language extension is enabled).
--
-- ==== __Examples__
--
-- > http "httpbin.org"
-- > -- http://httpbin.org
--
-- > https "httpbin.org"
-- > -- https://httpbin.org
--
-- > https "httpbin.org" /: "encoding" /: "utf8"
-- > -- https://httpbin.org/encoding/utf8
--
-- > https "httpbin.org" /: "foo" /: "bar/baz"
-- > -- https://httpbin.org/foo/bar%2Fbaz
--
-- > https "httpbin.org" /: "bytes" /~ (10 :: Int)
-- > -- https://httpbin.org/bytes/10
--
-- > https "юникод.рф"
-- > -- https://%D1%8E%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4.%D1%80%D1%84
data Url (scheme :: Scheme) = Url Scheme (NonEmpty Text)
  -- NOTE The second value is the path segments in reversed order.
  deriving (Eq, Ord, Show, Data, Typeable, Generic)

type role Url nominal

-- With template-haskell >=2.15 and text >=1.2.4 Lift can be derived, however
-- the derived lift forgets the type of the scheme.
instance (Typeable scheme) => TH.Lift (Url scheme) where
  lift url =
    TH.dataToExpQ (fmap liftText . cast) url `TH.sigE` case url of
      Url Http _ -> [t|Url 'Http|]
      Url Https _ -> [t|Url 'Https|]
    where
      liftText t = TH.AppE (TH.VarE 'T.pack) <$> TH.lift (T.unpack t)
  liftTyped = TH.Code . TH.unsafeTExpCoerce . TH.lift

-- | Given host name, produce a 'Url' which has “http” as its scheme and
-- empty path. This also sets port to @80@.
http :: Text -> Url 'Http
http = Url Http . pure

-- | Given host name, produce a 'Url' which has “https” as its scheme and
-- empty path. This also sets port to @443@.
https :: Text -> Url 'Https
https = Url Https . pure

-- | Grow a given 'Url' appending a single path segment to it. Note that the
-- path segment can be of any type that is an instance of 'ToHttpApiData'.
infixl 5 /~

(/~) :: (ToHttpApiData a) => Url scheme -> a -> Url scheme
Url secure path /~ segment = Url secure (NE.cons (toUrlPiece segment) path)

-- | A type-constrained version of @('/~')@ to remove ambiguity in the cases
-- when next URL piece is a 'Data.Text.Text' literal.
infixl 5 /:

(/:) :: Url scheme -> Text -> Url scheme
(/:) = (/~)

-- | Render a 'Url' as 'Text'.
--
-- @since 3.4.0
renderUrl :: Url scheme -> Text
renderUrl = \case
  Url Https parts ->
    "https://" <> renderParts parts
  Url Http parts ->
    "http://" <> renderParts parts
  where
    renderParts parts =
      T.intercalate "/" (reverse $ NE.toList parts)

-- | The 'useHttpURI' function provides an alternative method to get 'Url'
-- (possibly with some 'Option's) from a 'URI'. This is useful when you are
-- given a URL to query dynamically and don't know it beforehand.
--
-- This function expects the scheme to be “http” and host to be present.
--
-- @since 3.0.0
useHttpURI :: URI -> Maybe (Url 'Http, Option scheme)
useHttpURI uri = do
  guard (URI.uriScheme uri == Just [QQ.scheme|http|])
  urlHead <- http <$> uriHost uri
  let url = case URI.uriPath uri of
        Nothing -> urlHead
        Just uriPath -> uriPathToUrl uriPath urlHead
  return (url, uriOptions uri)

-- | Just like 'useHttpURI', but expects the “https” scheme.
--
-- @since 3.0.0
useHttpsURI :: URI -> Maybe (Url 'Https, Option scheme)
useHttpsURI uri = do
  guard (URI.uriScheme uri == Just [QQ.scheme|https|])
  urlHead <- https <$> uriHost uri
  let url = case URI.uriPath uri of
        Nothing -> urlHead
        Just uriPath -> uriPathToUrl uriPath urlHead
  return (url, uriOptions uri)

-- | Convert URI path to a 'Url'. Internal.
--
-- @since 3.9.0
uriPathToUrl ::
  (Bool, NonEmpty (URI.RText 'URI.PathPiece)) ->
  Url scheme ->
  Url scheme
uriPathToUrl (trailingSlash, xs) urlHead =
  if trailingSlash then path /: T.empty else path
  where
    path = foldl' (/:) urlHead (URI.unRText <$> NE.toList xs)

-- | A combination of 'useHttpURI' and 'useHttpsURI' for cases when scheme
-- is not known in advance.
--
-- @since 3.0.0
useURI ::
  URI ->
  Maybe
    ( Either
        (Url 'Http, Option scheme0)
        (Url 'Https, Option scheme1)
    )
useURI uri =
  (Left <$> useHttpURI uri) <|> (Right <$> useHttpsURI uri)

-- | An internal helper function to extract host from a 'URI'.
uriHost :: URI -> Maybe Text
uriHost uri = case URI.uriAuthority uri of
  Left _ -> Nothing
  Right URI.Authority {..} ->
    Just (URI.unRText authHost)

-- | A quasiquoter to build an 'Url' and 'Option' tuple. The type of the
-- generated expression is @('Url' scheme0, 'Option' scheme1)@ with
-- @scheme0@ being either 'Http' or 'Https' depending on the input.
--
-- @since 3.2.0
urlQ :: TH.QuasiQuoter
urlQ =
  TH.QuasiQuoter
    { quoteExp = \str ->
        case URI.mkURI (T.pack str) of
          Left err -> fail (displayException err)
          Right uri -> case useURI uri of
            Nothing -> fail "Not a HTTP or HTTPS URL"
            Just eurl ->
              TH.tupE
                [ either (TH.lift . fst) (TH.lift . fst) eurl,
                  [|uriOptions uri|]
                ],
      quotePat = error "This usage is not supported",
      quoteType = error "This usage is not supported",
      quoteDec = error "This usage is not supported"
    }

-- | An internal helper function to extract 'Option's from a 'URI'.
uriOptions :: forall scheme. URI -> Option scheme
uriOptions uri =
  mconcat
    [ auth,
      query,
      port'
      -- , fragment'
    ]
  where
    (auth, port') =
      case URI.uriAuthority uri of
        Left _ -> (mempty, mempty)
        Right URI.Authority {..} ->
          let auth0 = case authUserInfo of
                Nothing -> mempty
                Just URI.UserInfo {..} ->
                  let username = T.encodeUtf8 (URI.unRText uiUsername)
                      password = maybe "" (T.encodeUtf8 . URI.unRText) uiPassword
                   in basicAuthUnsafe username password
              port0 = case authPort of
                Nothing -> mempty
                Just port'' -> port (fromIntegral port'')
           in (auth0, port0)
    query =
      let liftQueryParam = \case
            URI.QueryFlag t -> queryFlag (URI.unRText t)
            URI.QueryParam k v -> URI.unRText k =: URI.unRText v
       in mconcat (liftQueryParam <$> URI.uriQuery uri)

-- TODO Blocked on upstream: https://github.com/snoyberg/http-client/issues/424
-- fragment' =
--   case URI.uriFragment uri of
--     Nothing -> mempty
--     Just fragment'' -> fragment (URI.unRText fragment'')

instance RequestComponent (Url scheme) where
  getRequestMod (Url scheme segments) = Endo $ \x ->
    let (host :| path) = NE.reverse segments
     in x
          { L.secure = case scheme of
              Http -> False
              Https -> True,
            L.port = case scheme of
              Http -> 80
              Https -> 443,
            L.host = Y.urlEncode False (T.encodeUtf8 host),
            L.path =
              (BL.toStrict . BB.toLazyByteString . Y.encodePathSegments) path
          }

----------------------------------------------------------------------------
-- Request—Body

-- $body
--
-- A number of options for request bodies are available. The @Content-Type@
-- header is set for you automatically according to the body option you use
-- (it's always specified in the documentation for a given body option). To
-- add your own way to represent request body, define an instance of
-- 'HttpBody'.

-- | This data type represents empty body of an HTTP request. This is the
-- data type to use with 'HttpMethod's that cannot have a body, as it's the
-- only type for which 'ProvidesBody' returns 'NoBody'.
--
-- Using of this body option does not set the @Content-Type@ header.
data NoReqBody = NoReqBody

instance HttpBody NoReqBody where
  getRequestBody NoReqBody = L.RequestBodyBS B.empty

-- | This body option allows us to use a JSON object as the request
-- body—probably the most popular format right now. Just wrap a data type
-- that is an instance of 'ToJSON' type class and you are done: it will be
-- converted to JSON and inserted as request body.
--
-- This body option sets the @Content-Type@ header to @\"application/json;
-- charset=utf-8\"@ value.
newtype ReqBodyJson a = ReqBodyJson a

instance (ToJSON a) => HttpBody (ReqBodyJson a) where
  getRequestBody (ReqBodyJson a) = L.RequestBodyLBS (A.encode a)
  getRequestContentType _ = pure "application/json; charset=utf-8"

-- | This body option streams request body from a file. It is expected that
-- the file size does not change during streaming.
--
-- Using of this body option does not set the @Content-Type@ header.
newtype ReqBodyFile = ReqBodyFile FilePath

instance HttpBody ReqBodyFile where
  getRequestBody (ReqBodyFile path) =
    LI.RequestBodyIO (L.streamFile path)

-- | HTTP request body represented by a strict 'ByteString'.
--
-- Using of this body option does not set the @Content-Type@ header.
newtype ReqBodyBs = ReqBodyBs ByteString

instance HttpBody ReqBodyBs where
  getRequestBody (ReqBodyBs bs) = L.RequestBodyBS bs

-- | HTTP request body represented by a lazy 'BL.ByteString'.
--
-- Using of this body option does not set the @Content-Type@ header.
newtype ReqBodyLbs = ReqBodyLbs BL.ByteString

instance HttpBody ReqBodyLbs where
  getRequestBody (ReqBodyLbs bs) = L.RequestBodyLBS bs

-- | URL-encoded body. This can hold a collection of parameters which are
-- encoded similarly to query parameters at the end of query string, with
-- the only difference that they are stored in request body. The similarity
-- is reflected in the API as well, as you can use the same combinators you
-- would use to add query parameters: @('=:')@ and 'queryFlag'.
--
-- This body option sets the @Content-Type@ header to
-- @\"application/x-www-form-urlencoded\"@ value.
newtype ReqBodyUrlEnc = ReqBodyUrlEnc FormUrlEncodedParam

instance HttpBody ReqBodyUrlEnc where
  getRequestBody (ReqBodyUrlEnc (FormUrlEncodedParam params)) =
    (L.RequestBodyLBS . BB.toLazyByteString) (Y.renderQueryText False params)
  getRequestContentType _ = pure "application/x-www-form-urlencoded"

-- | An opaque monoidal value that allows to collect URL-encoded parameters
-- to be wrapped in 'ReqBodyUrlEnc'.
newtype FormUrlEncodedParam = FormUrlEncodedParam [(Text, Maybe Text)]
  deriving (Semigroup, Monoid)

instance QueryParam FormUrlEncodedParam where
  queryParam name mvalue =
    FormUrlEncodedParam [(name, toQueryParam <$> mvalue)]
  queryParamToList (FormUrlEncodedParam p) = p

-- | Use 'formToQuery'.
--
-- @since 3.11.0
instance FromForm FormUrlEncodedParam where
  fromForm = Right . formToQuery

-- | Multipart form data. Please consult the
-- "Network.HTTP.Client.MultipartFormData" module for how to construct
-- parts, then use 'reqBodyMultipart' to create actual request body from the
-- parts. 'reqBodyMultipart' is the only way to get a value of the type
-- 'ReqBodyMultipart', as its constructor is not exported on purpose.
--
-- @since 0.2.0
--
-- ==== __Examples__
--
-- > import Control.Monad.IO.Class
-- > import Data.Default.Class
-- > import Network.HTTP.Req
-- > import qualified Network.HTTP.Client.MultipartFormData as LM
-- >
-- > main :: IO ()
-- > main = runReq def $ do
-- >   body <-
-- >     reqBodyMultipart
-- >       [ LM.partBS "title" "My Image"
-- >       , LM.partFileSource "file1" "/tmp/image.jpg"
-- >       ]
-- >   response <-
-- >     req POST (http "example.com" /: "post")
-- >       body
-- >       bsResponse
-- >       mempty
-- >   liftIO $ print (responseBody response)
data ReqBodyMultipart = ReqBodyMultipart ByteString LI.RequestBody

instance HttpBody ReqBodyMultipart where
  getRequestBody (ReqBodyMultipart _ body) = body
  getRequestContentType (ReqBodyMultipart boundary _) =
    pure ("multipart/form-data; boundary=" <> boundary)

-- | Create 'ReqBodyMultipart' request body from a collection of 'LM.Part's.
--
-- @since 0.2.0
reqBodyMultipart :: (MonadIO m) => [LM.Part] -> m ReqBodyMultipart
reqBodyMultipart parts = liftIO $ do
  boundary <- LM.webkitBoundary
  body <- LM.renderParts boundary parts
  return (ReqBodyMultipart boundary body)

-- | A type class for things that can be interpreted as an HTTP
-- 'L.RequestBody'.
class HttpBody body where
  -- | How to get actual 'L.RequestBody'.
  getRequestBody :: body -> L.RequestBody

  -- | This method allows us to optionally specify the value of
  -- @Content-Type@ header that should be used with particular body option.
  -- By default it returns 'Nothing' and so @Content-Type@ is not set.
  getRequestContentType :: body -> Maybe ByteString
  getRequestContentType = const Nothing

-- | The type function recognizes 'NoReqBody' as having 'NoBody', while any
-- other body option 'CanHaveBody'. This forces the user to use 'NoReqBody'
-- with 'GET' method and other methods that should not have body.
type family ProvidesBody body :: CanHaveBody where
  ProvidesBody NoReqBody = 'NoBody
  ProvidesBody body = 'CanHaveBody

-- | This type function allows any HTTP body if method says it
-- 'CanHaveBody'. When the method says it should have 'NoBody', the only
-- body option to use is 'NoReqBody'.
type family
  HttpBodyAllowed
    (allowsBody :: CanHaveBody)
    (providesBody :: CanHaveBody) ::
    Constraint
  where
  HttpBodyAllowed 'NoBody 'NoBody = ()
  HttpBodyAllowed 'CanHaveBody body = ()
  HttpBodyAllowed 'NoBody 'CanHaveBody =
    TypeError
      ('Text "This HTTP method does not allow attaching a request body.")

instance (HttpBody body) => RequestComponent (Tagged "body" body) where
  getRequestMod (Tagged body) = Endo $ \x ->
    x
      { L.requestBody = getRequestBody body,
        L.requestHeaders =
          let old = L.requestHeaders x
           in case getRequestContentType body of
                Nothing -> old
                Just contentType ->
                  (Y.hContentType, contentType) : old
      }

----------------------------------------------------------------------------
-- Request—Optional parameters

-- $optional-parameters
--
-- Optional parameters of request include things like query parameters,
-- headers, port number, etc. All optional parameters have the type
-- 'Option', which is a 'Monoid'. This means that you can use 'mempty' as
-- the last argument of 'req' to specify no optional parameters, or combine
-- 'Option's using 'mappend' or @('<>')@ to have several of them at once.

-- | The opaque 'Option' type is a 'Monoid' you can use to pack collection
-- of optional parameters like query parameters and headers. See sections
-- below to learn which 'Option' primitives are available.
data Option (scheme :: Scheme)
  = Option (Endo (Y.QueryText, L.Request)) (Maybe (L.Request -> IO L.Request))

-- NOTE 'QueryText' is just [(Text, Maybe Text)], we keep it along with
-- Request to avoid appending to an existing query string in request every
-- time new parameter is added. The additional Maybe (L.Request -> IO
-- L.Request) is a finalizer that will be applied after all other
-- transformations. This is for authentication methods that sign requests
-- based on data in Request.

instance Semigroup (Option scheme) where
  Option er0 mr0 <> Option er1 mr1 =
    Option
      (er0 <> er1)
      (mr0 <|> mr1)

instance Monoid (Option scheme) where
  mempty = Option mempty Nothing
  mappend = (<>)

-- | Use 'formToQuery'.
--
-- @since 3.11.0
instance FromForm (Option scheme) where
  fromForm = Right . formToQuery

-- | A helper to create an 'Option' that modifies only collection of query
-- parameters. This helper is not a part of the public API.
withQueryParams :: (Y.QueryText -> Y.QueryText) -> Option scheme
withQueryParams f = Option (Endo (first f)) Nothing

-- | A helper to create an 'Option' that modifies only 'L.Request'. This
-- helper is not a part of public API.
withRequest :: (L.Request -> L.Request) -> Option scheme
withRequest f = Option (Endo (second f)) Nothing

instance RequestComponent (Option scheme) where
  getRequestMod (Option f _) = Endo $ \x ->
    let (qparams, x') = appEndo f ([], x)
        query = Y.renderQuery True (Y.queryTextToQuery qparams)
     in x' {L.queryString = query}

-- | Finalize given 'L.Request' by applying a finalizer from the given
-- 'Option' (if it has any).
finalizeRequest :: (MonadIO m) => Option scheme -> L.Request -> m L.Request
finalizeRequest (Option _ mfinalizer) = liftIO . fromMaybe pure mfinalizer

----------------------------------------------------------------------------
-- Request—Optional parameters—Query Parameters

-- $query-parameters
--
-- This section describes a polymorphic interface that can be used to
-- construct query parameters (of the type 'Option') and form URL-encoded
-- bodies (of the type 'FormUrlEncodedParam').

-- | This operator builds a query parameter that will be included in URL of
-- your request after the question sign @?@. This is the same syntax you use
-- with form URL encoded request bodies.
--
-- This operator is defined in terms of 'queryParam':
--
-- > name =: value = queryParam name (pure value)
infix 7 =:

(=:) :: (QueryParam param, ToHttpApiData a) => Text -> a -> param
name =: value = queryParam name (pure value)

-- | Construct a flag, that is, a valueless query parameter. For example, in
-- the following URL @\"a\"@ is a flag, while @\"b\"@ is a query parameter
-- with a value:
--
-- > https://httpbin.org/foo/bar?a&b=10
--
-- This operator is defined in terms of 'queryParam':
--
-- > queryFlag name = queryParam name (Nothing :: Maybe ())
queryFlag :: (QueryParam param) => Text -> param
queryFlag name = queryParam name (Nothing :: Maybe ())

-- | Construct query parameters from a 'ToForm' instance. This function
-- produces the same query params as 'Form.urlEncodeAsFormStable'.
--
-- Note that 'Form.Form' doesn't have the concept of parameters with the
-- empty value (i.e. what you can get by @key =: ""@). If the value is
-- empty, it will be encoded as a valueless parameter (i.e. what you can get
-- by @queryFlag key@).
--
-- @since 3.11.0
formToQuery :: (QueryParam param, Monoid param, ToForm f) => f -> param
formToQuery f = mconcat . fmap toParam . Form.toListStable $ toForm f
  where
    toParam (key, val) =
      queryParam key $
        if val == ""
          then Nothing
          else Just val

-- | A type class for query-parameter-like things. The reason to have an
-- overloaded 'queryParam' is to be able to use it as an 'Option' and as a
-- 'FormUrlEncodedParam' when constructing form URL encoded request bodies.
-- Having the same syntax for these cases seems natural and user-friendly.
class QueryParam param where
  -- | Create a query parameter with given name and value. If value is
  -- 'Nothing', it won't be included at all (i.e. you create a flag this
  -- way). It's recommended to use @('=:')@ and 'queryFlag' instead of this
  -- method, because they are easier to read.
  queryParam :: (ToHttpApiData a) => Text -> Maybe a -> param

  -- | Get the query parameter names and values set by 'queryParam'.
  --
  -- @since 3.11.0
  queryParamToList :: param -> [(Text, Maybe Text)]

instance QueryParam (Option scheme) where
  queryParam name mvalue =
    withQueryParams ((:) (name, toQueryParam <$> mvalue))
  queryParamToList (Option f _) = fst $ appEndo f ([], L.defaultRequest)

----------------------------------------------------------------------------
-- Request—Optional parameters—Headers

-- | Create an 'Option' that adds a header. Note that if you 'mappend' two
-- headers with the same names the leftmost header will win. This means, in
-- particular, that you cannot create a request with several headers of the
-- same name.
header ::
  -- | Header name
  ByteString ->
  -- | Header value
  ByteString ->
  Option scheme
header name value = withRequest (attachHeader name value)

-- | Attach a header with given name and content to a 'L.Request'.
--
-- @since 1.1.0
attachHeader :: ByteString -> ByteString -> L.Request -> L.Request
attachHeader name value x =
  x {L.requestHeaders = (CI.mk name, value) : L.requestHeaders x}

-- | Same as 'header', but with redacted values on print.
--
-- @since 3.13.0
headerRedacted :: ByteString -> ByteString -> Option scheme
headerRedacted name value = withRequest $ \x ->
  let y = attachHeader name value x
   in y {L.redactHeaders = CI.mk name `S.insert` L.redactHeaders y}

----------------------------------------------------------------------------
-- Request—Optional parameters—Cookies

-- $cookies
--
-- Support for cookies is quite minimalistic at the moment. It's possible to
-- specify which cookies to send using 'cookieJar' and inspect 'L.Response'
-- to extract 'L.CookieJar' from it (see 'responseCookieJar').

-- | Use the given 'L.CookieJar'. A 'L.CookieJar' can be obtained from a
-- 'L.Response' record.
cookieJar :: L.CookieJar -> Option scheme
cookieJar jar = withRequest $ \x ->
  x {L.cookieJar = Just jar}

----------------------------------------------------------------------------
-- Request—Optional parameters—Authentication

-- $authentication
--
-- This section provides the common authentication helpers in the form of
-- 'Option's. You should always prefer the provided authentication 'Option's
-- to manual construction of headers because it ensures that you only use
-- one authentication method at a time (they overwrite each other) and
-- provides additional type safety that prevents leaking of credentials in
-- the cases when authentication relies on HTTPS for encrypting sensitive
-- data.

-- | The 'Option' adds basic authentication.
--
-- See also: <https://en.wikipedia.org/wiki/Basic_access_authentication>.
basicAuth ::
  -- | Username
  ByteString ->
  -- | Password
  ByteString ->
  -- | Auth 'Option'
  Option 'Https
basicAuth = basicAuthUnsafe

-- | An alternative to 'basicAuth' which works for any scheme. Note that
-- using basic access authentication without SSL\/TLS is vulnerable to
-- attacks. Use 'basicAuth' instead unless you know what you are doing.
--
-- @since 0.3.1
basicAuthUnsafe ::
  -- | Username
  ByteString ->
  -- | Password
  ByteString ->
  -- | Auth 'Option'
  Option scheme
basicAuthUnsafe username password =
  customAuth
    (pure . L.applyBasicAuth username password)

-- | The 'Option' set basic proxy authentication header.
--
-- @since 1.1.0
basicProxyAuth ::
  -- | Username
  ByteString ->
  -- | Password
  ByteString ->
  -- | Auth 'Option'
  Option scheme
basicProxyAuth username password =
  withRequest (L.applyBasicProxyAuth username password)

-- | The 'Option' adds OAuth1 authentication.
--
-- @since 0.2.0
oAuth1 ::
  -- | Consumer token
  ByteString ->
  -- | Consumer secret
  ByteString ->
  -- | OAuth token
  ByteString ->
  -- | OAuth token secret
  ByteString ->
  -- | Auth 'Option'
  Option scheme
oAuth1 consumerToken consumerSecret token tokenSecret =
  customAuth (OAuth.signOAuth app creds)
  where
    app =
      OAuth.newOAuth
        { OAuth.oauthConsumerKey = consumerToken,
          OAuth.oauthConsumerSecret = consumerSecret
        }
    creds = OAuth.newCredential token tokenSecret

-- | The 'Option' adds an OAuth2 bearer token. This is treated by many
-- services as the equivalent of a username and password.
--
-- The 'Option' is defined as:
--
-- > oAuth2Bearer token = header "Authorization" ("Bearer " <> token)
--
-- See also: <https://en.wikipedia.org/wiki/OAuth>.
oAuth2Bearer ::
  -- | Token
  ByteString ->
  -- | Auth 'Option'
  Option 'Https
oAuth2Bearer token =
  customAuth
    (pure . attachHeader "Authorization" ("Bearer " <> token))

-- | The 'Option' adds a not-quite-standard OAuth2 bearer token (that seems
-- to be used only by GitHub). This will be treated by whatever services
-- accept it as the equivalent of a username and password.
--
-- The 'Option' is defined as:
--
-- > oAuth2Token token = header "Authorization" ("token" <> token)
--
-- See also: <https://developer.github.com/v3/oauth#3-use-the-access-token-to-access-the-api>.
oAuth2Token ::
  -- | Token
  ByteString ->
  -- | Auth 'Option'
  Option 'Https
oAuth2Token token =
  customAuth
    (pure . attachHeader "Authorization" ("token " <> token))

-- | A helper to create custom authentication 'Option's. The given
-- 'IO'-enabled request transformation is applied after all other
-- modifications when constructing a request. Use wisely.
--
-- @since 1.1.0
customAuth :: (L.Request -> IO L.Request) -> Option scheme
customAuth = Option mempty . pure

----------------------------------------------------------------------------
-- Request—Optional parameters—Other

-- | Specify the port to connect to explicitly. Normally, 'Url' you use
-- determines the default port: @80@ for HTTP and @443@ for HTTPS. This
-- 'Option' allows us to choose an arbitrary port overwriting the defaults.
port :: Int -> Option scheme
port n = withRequest $ \x ->
  x {L.port = n}

-- | This 'Option' controls whether gzipped data should be decompressed on
-- the fly. By default everything except for @\"application\/x-tar\"@ is
-- decompressed, i.e. we have:
--
-- > decompress (/= "application/x-tar")
--
-- You can also choose to decompress everything like this:
--
-- > decompress (const True)
decompress ::
  -- | Predicate that is given MIME type, it returns 'True' when content
  -- should be decompressed on the fly.
  (ByteString -> Bool) ->
  Option scheme
decompress f = withRequest $ \x ->
  x {L.decompress = f}

-- | Specify the number of microseconds to wait for response. The default
-- value is 30 seconds (defined in 'L.ManagerSettings' of connection
-- 'L.Manager').
responseTimeout ::
  -- | Number of microseconds to wait
  Int ->
  Option scheme
responseTimeout n = withRequest $ \x ->
  x {L.responseTimeout = LI.ResponseTimeoutMicro n}

-- | HTTP version to send to the server, the default is HTTP 1.1.
httpVersion ::
  -- | Major version number
  Int ->
  -- | Minor version number
  Int ->
  Option scheme
httpVersion major minor = withRequest $ \x ->
  x {L.requestVersion = Y.HttpVersion major minor}

----------------------------------------------------------------------------
-- Response interpretations

-- | Make a request and ignore the body of the response.
newtype IgnoreResponse = IgnoreResponse (L.Response ())
  deriving (Show)

instance HttpResponse IgnoreResponse where
  type HttpResponseBody IgnoreResponse = ()
  toVanillaResponse (IgnoreResponse r) = r
  getHttpResponse r = return $ IgnoreResponse (void r)

-- | Use this as the fourth argument of 'req' to specify that you want it to
-- ignore the response body.
ignoreResponse :: Proxy IgnoreResponse
ignoreResponse = Proxy

-- | Make a request and interpret the body of the response as JSON. The
-- 'handleHttpException' method of 'MonadHttp' instance corresponding to
-- monad in which you use 'req' will determine what to do in the case when
-- parsing fails (the 'JsonHttpException' constructor will be used).
newtype JsonResponse a = JsonResponse (L.Response a)
  deriving (Show)

instance (FromJSON a) => HttpResponse (JsonResponse a) where
  type HttpResponseBody (JsonResponse a) = a
  toVanillaResponse (JsonResponse r) = r
  getHttpResponse r = do
    chunks <- L.brConsume (L.responseBody r)
    case A.eitherDecode (BL.fromChunks chunks) of
      Left e -> throwIO (JsonHttpException e)
      Right x -> return $ JsonResponse (x <$ r)
  acceptHeader Proxy = Just "application/json"

-- | Use this as the fourth argument of 'req' to specify that you want it to
-- return the 'JsonResponse' interpretation.
jsonResponse :: Proxy (JsonResponse a)
jsonResponse = Proxy

-- | Make a request and interpret the body of the response as a strict
-- 'ByteString'.
newtype BsResponse = BsResponse (L.Response ByteString)
  deriving (Show)

instance HttpResponse BsResponse where
  type HttpResponseBody BsResponse = ByteString
  toVanillaResponse (BsResponse r) = r
  getHttpResponse r = do
    chunks <- L.brConsume (L.responseBody r)
    return $ BsResponse (B.concat chunks <$ r)

-- | Use this as the fourth argument of 'req' to specify that you want to
-- interpret the response body as a strict 'ByteString'.
bsResponse :: Proxy BsResponse
bsResponse = Proxy

-- | Make a request and interpret the body of the response as a lazy
-- 'BL.ByteString'.
newtype LbsResponse = LbsResponse (L.Response BL.ByteString)
  deriving (Show)

instance HttpResponse LbsResponse where
  type HttpResponseBody LbsResponse = BL.ByteString
  toVanillaResponse (LbsResponse r) = r
  getHttpResponse r = do
    chunks <- L.brConsume (L.responseBody r)
    return $ LbsResponse (BL.fromChunks chunks <$ r)

-- | Use this as the fourth argument of 'req' to specify that you want to
-- interpret the response body as a lazy 'BL.ByteString'.
lbsResponse :: Proxy LbsResponse
lbsResponse = Proxy

----------------------------------------------------------------------------
-- Helpers for response interpretations

-- | Fetch beginning of the response and return it together with a new
-- @'L.Response' 'L.BodyReader'@ that can be passed to 'getHttpResponse' and
-- such.
grabPreview ::
  -- | How many bytes to fetch
  Int ->
  -- | Response with body reader inside
  L.Response L.BodyReader ->
  -- | Preview 'ByteString' and new response with body reader inside
  IO (ByteString, L.Response L.BodyReader)
grabPreview nbytes r = do
  let br = L.responseBody r
  (target, leftover, done) <- brReadN br nbytes
  nref <- newIORef (0 :: Int)
  let br' = do
        n <- readIORef nref
        let incn = modifyIORef' nref (+ 1)
        case n of
          0 -> do
            incn
            if B.null target
              then br'
              else return target
          1 -> do
            incn
            if B.null leftover
              then br'
              else return leftover
          _ ->
            if done
              then return B.empty
              else br
  return (target, r {L.responseBody = br'})

-- | Consume N bytes from 'L.BodyReader', return the target chunk, the
-- leftover (may be empty), and whether we're done consuming the body.
brReadN ::
  -- | Body reader to stream from
  L.BodyReader ->
  -- | How many bytes to consume
  Int ->
  -- | Target chunk, the leftover, whether we're done
  IO (ByteString, ByteString, Bool)
brReadN br n = go 0 id id
  where
    go !tlen t l = do
      chunk <- br
      if B.null chunk
        then return (r t, r l, True)
        else do
          let (target, leftover) = B.splitAt (n - tlen) chunk
              tlen' = B.length target
              t' = t . (target :)
              l' = l . (leftover :)
          if tlen + tlen' < n
            then go (tlen + tlen') t' l'
            else return (r t', r l', False)
    r f = B.concat (f [])

----------------------------------------------------------------------------
-- Inspecting a response

-- | Get the response body.
responseBody ::
  (HttpResponse response) =>
  response ->
  HttpResponseBody response
responseBody = L.responseBody . toVanillaResponse

-- | Get the response status code.
responseStatusCode ::
  (HttpResponse response) =>
  response ->
  Int
responseStatusCode =
  Y.statusCode . L.responseStatus . toVanillaResponse

-- | Get the response status message.
responseStatusMessage ::
  (HttpResponse response) =>
  response ->
  ByteString
responseStatusMessage =
  Y.statusMessage . L.responseStatus . toVanillaResponse

-- | Lookup a particular header from a response.
responseHeader ::
  (HttpResponse response) =>
  -- | Response interpretation
  response ->
  -- | Header to lookup
  ByteString ->
  -- | Header value if found
  Maybe ByteString
responseHeader r h =
  (lookup (CI.mk h) . L.responseHeaders . toVanillaResponse) r

-- | Get the response 'L.CookieJar'.
responseCookieJar ::
  (HttpResponse response) =>
  response ->
  L.CookieJar
responseCookieJar = L.responseCookieJar . toVanillaResponse

----------------------------------------------------------------------------
-- Response—Defining your own interpretation

-- $new-response-interpretation
--
-- To create a new response interpretation you just need to make your data
-- type an instance of the 'HttpResponse' type class.

-- | A type class for response interpretations. It allows us to describe how
-- to consume the response from a @'L.Response' 'L.BodyReader'@ and produce
-- the final result that is to be returned to the user.
class HttpResponse response where
  -- | The associated type is the type of body that can be extracted from an
  -- instance of 'HttpResponse'.
  type HttpResponseBody response :: Type

  -- | The method describes how to get the underlying 'L.Response' record.
  toVanillaResponse :: response -> L.Response (HttpResponseBody response)

  -- | This method describes how to consume response body and, more
  -- generally, obtain @response@ value from @'L.Response' 'L.BodyReader'@.
  --
  -- __Note__: 'L.BodyReader' is nothing but @'IO' 'ByteString'@. You should
  -- call this action repeatedly until it yields the empty 'ByteString'. In
  -- that case streaming of response is finished (which apparently leads to
  -- closing of the connection, so don't call the reader after it has
  -- returned the empty 'ByteString' once) and you can concatenate the
  -- chunks to obtain the final result. (Of course you could as well stream
  -- the contents to a file or do whatever you want.)
  --
  -- __Note__: signature of this function was changed in the version
  -- /1.0.0/.
  getHttpResponse ::
    -- | Response with body reader inside
    L.Response L.BodyReader ->
    -- | The final result
    IO response

  -- | The value of @\"Accept\"@ header. This is useful, for example, if a
  -- website supports both @XML@ and @JSON@ responses, and decides what to
  -- reply with based on what @Accept@ headers you have sent.
  --
  -- __Note__: manually specified 'Options' that set the @\"Accept\"@ header
  -- will take precedence.
  --
  -- @since 2.1.0
  acceptHeader :: Proxy response -> Maybe ByteString
  acceptHeader Proxy = Nothing

-- | This instance has been added to make it easier to inspect 'L.Response'
-- using Req's functions like 'responseStatusCode', 'responseStatusMessage',
-- etc.
--
-- @since 3.12.0
instance HttpResponse (L.Response ()) where
  type HttpResponseBody (L.Response ()) = ()
  toVanillaResponse = id
  getHttpResponse = return . void

----------------------------------------------------------------------------
-- Other

-- | The main class for things that are “parts” of 'L.Request' in the sense
-- that if we have a 'L.Request', then we know how to apply an instance of
-- 'RequestComponent' changing\/overwriting something in it. 'Endo' is a
-- monoid of endomorphisms under composition, it's used to chain different
-- request components easier using @('<>')@.
--
-- __Note__: this type class is not a part of the public API.
class RequestComponent a where
  -- | Get a function that takes a 'L.Request' and changes it somehow
  -- returning another 'L.Request'. For example, the 'HttpMethod' instance
  -- of 'RequestComponent' just overwrites method. The function is wrapped
  -- in 'Endo' so it's easier to chain such “modifying applications”
  -- together building bigger and bigger 'RequestComponent's.
  getRequestMod :: a -> Endo L.Request

-- | This wrapper is only used to attach a type-level tag to a given type.
-- This is necessary to define instances of 'RequestComponent' for any thing
-- that implements 'HttpMethod' or 'HttpBody'. Without the tag, GHC can't
-- see the difference between @'HttpMethod' method => 'RequestComponent'
-- method@ and @'HttpBody' body => 'RequestComponent' body@ when it decides
-- which instance to use (i.e. the constraints are taken into account later,
-- when instance is already chosen).
newtype Tagged (tag :: Symbol) a = Tagged a

-- | Exceptions that this library throws.
data HttpException
  = -- | A wrapper with an 'L.HttpException' from "Network.HTTP.Client"
    VanillaHttpException L.HttpException
  | -- | A wrapper with Aeson-produced 'String' describing why decoding
    -- failed
    JsonHttpException String
  deriving (Show, Typeable, Generic)

instance Exception HttpException

-- | Return 'Just' if the given 'HttpException' is wrapping a http-client's
-- 'L.StatusCodeException'. Otherwise, return 'Nothing'.
--
-- @since 3.12.0
isStatusCodeException :: HttpException -> Maybe (L.Response ())
isStatusCodeException
  ( VanillaHttpException
      ( L.HttpExceptionRequest
          _
          (L.StatusCodeException r _)
        )
    ) = Just r
isStatusCodeException _ = Nothing

-- | A simple type isomorphic to 'Bool' that we only have for better error
-- messages. We use it as a kind and its data constructors as type-level
-- tags.
--
-- See also: 'HttpMethod' and 'HttpBody'.
data CanHaveBody
  = -- | Indeed can have a body
    CanHaveBody
  | -- | Should not have a body
    NoBody

-- | A type-level tag that specifies URL scheme used (and thus if HTTPS is
-- enabled). This is used to force TLS requirement for some authentication
-- 'Option's.
data Scheme
  = -- | HTTP
    Http
  | -- | HTTPS
    Https
  deriving (Eq, Ord, Show, Data, Typeable, Generic, TH.Lift)