-
Notifications
You must be signed in to change notification settings - Fork 27
/
wisp.gleam
1836 lines (1703 loc) · 51.7 KB
/
wisp.gleam
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
import exception
import gleam/bit_array
import gleam/bool
import gleam/bytes_builder.{type BytesBuilder}
import gleam/crypto
import gleam/dict.{type Dict}
import gleam/dynamic.{type Dynamic}
import gleam/erlang
import gleam/erlang/atom.{type Atom}
import gleam/http.{type Method}
import gleam/http/cookie
import gleam/http/request.{type Request as HttpRequest}
import gleam/http/response.{
type Response as HttpResponse, Response as HttpResponse,
}
import gleam/int
import gleam/json
import gleam/list
import gleam/option.{type Option}
import gleam/result
import gleam/string
import gleam/string_builder.{type StringBuilder}
import gleam/uri
import logging
import marceau
import mist
import simplifile
//
// Running the server
//
/// Convert a Wisp request handler into a function that can be run with the Mist
/// web server.
///
/// # Examples
///
/// ```gleam
/// pub fn main() {
/// let secret_key_base = "..."
/// let assert Ok(_) =
/// handle_request
/// |> wisp.mist_handler(secret_key_base)
/// |> mist.new
/// |> mist.port(8000)
/// |> mist.start_http
/// process.sleep_forever()
/// }
/// ```
pub fn mist_handler(
handler: fn(Request) -> Response,
secret_key_base: String,
) -> fn(HttpRequest(mist.Connection)) -> HttpResponse(mist.ResponseData) {
fn(request: HttpRequest(_)) {
let connection = make_connection(mist_body_reader(request), secret_key_base)
let request = request.set_body(request, connection)
use <- exception.defer(fn() {
let assert Ok(_) = delete_temporary_files(request)
})
let response =
request
|> handler
|> mist_response
response
}
}
fn mist_body_reader(request: HttpRequest(mist.Connection)) -> Reader {
case mist.stream(request) {
Error(_) -> fn(_) { Ok(ReadingFinished) }
Ok(stream) -> fn(size) { wrap_mist_chunk(stream(size)) }
}
}
fn wrap_mist_chunk(
chunk: Result(mist.Chunk, mist.ReadError),
) -> Result(Read, Nil) {
chunk
|> result.nil_error
|> result.map(fn(chunk) {
case chunk {
mist.Done -> ReadingFinished
mist.Chunk(data, consume) ->
Chunk(data, fn(size) { wrap_mist_chunk(consume(size)) })
}
})
}
fn mist_response(response: Response) -> HttpResponse(mist.ResponseData) {
let body = case response.body {
Empty -> mist.Bytes(bytes_builder.new())
Text(text) -> mist.Bytes(bytes_builder.from_string_builder(text))
Bytes(bytes) -> mist.Bytes(bytes)
File(path) -> mist_send_file(path)
}
response
|> response.set_body(body)
}
fn mist_send_file(path: String) -> mist.ResponseData {
case mist.send_file(path, offset: 0, limit: option.None) {
Ok(body) -> body
Error(error) -> {
log_error(string.inspect(error))
// TODO: return 500
mist.Bytes(bytes_builder.new())
}
}
}
//
// Responses
//
/// The body of a HTTP response, to be sent to the client.
///
pub type Body {
/// A body of unicode text.
///
/// The body is represented using a `StringBuilder`. If you have a `String`
/// you can use the `string_builder.from_string` function to convert it.
///
Text(StringBuilder)
/// A body of binary data.
///
/// The body is represented using a `StringBuilder`. If you have a `String`
/// you can use the `string_builder.from_string` function to convert it.
///
Bytes(BytesBuilder)
/// A body of the contents of a file.
///
/// This will be sent efficiently using the `send_file` function of the
/// underlying HTTP server. The file will not be read into memory so it is
/// safe to send large files this way.
///
File(path: String)
/// An empty body. This may be returned by the `require_*` middleware
/// functions in the event of a failure, invalid request, or other situation
/// in which the request cannot be processed.
///
/// Your application may wish to use a middleware to provide default responses
/// in place of any with an empty body.
///
Empty
}
/// An alias for a HTTP response containing a `Body`.
pub type Response =
HttpResponse(Body)
/// Create an empty response with the given status code.
///
/// # Examples
///
/// ```gleam
/// response(200)
/// // -> Response(200, [], Empty)
/// ```
///
pub fn response(status: Int) -> Response {
HttpResponse(status, [], Empty)
}
/// Set the body of a response.
///
/// # Examples
///
/// ```gleam
/// response(200)
/// |> set_body(File("/tmp/myfile.txt"))
/// // -> Response(200, [], File("/tmp/myfile.txt"))
/// ```
///
pub fn set_body(response: Response, body: Body) -> Response {
response
|> response.set_body(body)
}
/// Send a file from the disc as a file download.
///
/// The operating system `send_file` function is used to efficiently send the
/// file over the network socket without reading the entire file into memory.
///
/// The `content-disposition` header will be set to `attachment;
/// filename="name"` to ensure the file is downloaded by the browser. This is
/// especially good for files that the browser would otherwise attempt to open
/// as this can result in cross-site scripting vulnerabilities.
///
/// If you wish to not set the `content-disposition` header you could use the
/// `set_body` function with the `File` body variant.
///
/// # Examples
///
/// ```gleam
/// response(200)
/// |> file_download(named: "myfile.txt", from: "/tmp/myfile.txt")
/// // -> Response(
/// // 200,
/// // [#("content-disposition", "attachment; filename=\"myfile.txt\"")],
/// // File("/tmp/myfile.txt"),
/// // )
/// ```
///
pub fn file_download(
response: Response,
named name: String,
from path: String,
) -> Response {
let name = uri.percent_encode(name)
response
|> response.set_header(
"content-disposition",
"attachment; filename=\"" <> name <> "\"",
)
|> response.set_body(File(path))
}
/// Send a file from memory as a file download.
///
/// If your file is already on the disc use `file_download` instead, to avoid
/// having to read the file into memory to send it.
///
/// The `content-disposition` header will be set to `attachment;
/// filename="name"` to ensure the file is downloaded by the browser. This is
/// especially good for files that the browser would otherwise attempt to open
/// as this can result in cross-site scripting vulnerabilities.
///
/// # Examples
///
/// ```gleam
/// response(200)
/// |> file_download_from_memory(named: "myfile.txt", containing: "Hello, Joe!")
/// // -> Response(
/// // 200,
/// // [#("content-disposition", "attachment; filename=\"myfile.txt\"")],
/// // File("/tmp/myfile.txt"),
/// // )
/// ```
///
pub fn file_download_from_memory(
response: Response,
named name: String,
containing data: BytesBuilder,
) -> Response {
let name = uri.percent_encode(name)
response
|> response.set_header(
"content-disposition",
"attachment; filename=\"" <> name <> "\"",
)
|> response.set_body(Bytes(data))
}
/// Create a HTML response.
///
/// The body is expected to be valid HTML, though this is not validated.
/// The `content-type` header will be set to `text/html`.
///
/// # Examples
///
/// ```gleam
/// let body = string_builder.from_string("<h1>Hello, Joe!</h1>")
/// html_response(body, 200)
/// // -> Response(200, [#("content-type", "text/html")], Text(body))
/// ```
///
pub fn html_response(html: StringBuilder, status: Int) -> Response {
HttpResponse(status, [#("content-type", "text/html")], Text(html))
}
/// Create a JSON response.
///
/// The body is expected to be valid JSON, though this is not validated.
/// The `content-type` header will be set to `application/json`.
///
/// # Examples
///
/// ```gleam
/// let body = string_builder.from_string("{\"name\": \"Joe\"}")
/// json_response(body, 200)
/// // -> Response(200, [#("content-type", "application/json")], Text(body))
/// ```
///
pub fn json_response(json: StringBuilder, status: Int) -> Response {
HttpResponse(status, [#("content-type", "application/json")], Text(json))
}
/// Set the body of a response to a given HTML document, and set the
/// `content-type` header to `text/html`.
///
/// The body is expected to be valid HTML, though this is not validated.
///
/// # Examples
///
/// ```gleam
/// let body = string_builder.from_string("<h1>Hello, Joe!</h1>")
/// response(201)
/// |> html_body(body)
/// // -> Response(201, [#("content-type", "text/html")], Text(body))
/// ```
///
pub fn html_body(response: Response, html: StringBuilder) -> Response {
response
|> response.set_body(Text(html))
|> response.set_header("content-type", "text/html")
}
/// Set the body of a response to a given JSON document, and set the
/// `content-type` header to `application/json`.
///
/// The body is expected to be valid JSON, though this is not validated.
///
/// # Examples
///
/// ```gleam
/// let body = string_builder.from_string("{\"name\": \"Joe\"}")
/// response(201)
/// |> json_body(body)
/// // -> Response(201, [#("content-type", "application/json")], Text(body))
/// ```
///
pub fn json_body(response: Response, json: StringBuilder) -> Response {
response
|> response.set_body(Text(json))
|> response.set_header("content-type", "application/json")
}
/// Set the body of a response to a given string builder.
///
/// You likely want to also set the request `content-type` header to an
/// appropriate value for the format of the content.
///
/// # Examples
///
/// ```gleam
/// let body = string_builder.from_string("Hello, Joe!")
/// response(201)
/// |> string_builder_body(body)
/// // -> Response(201, [], Text(body))
/// ```
///
pub fn string_builder_body(
response: Response,
content: StringBuilder,
) -> Response {
response
|> response.set_body(Text(content))
}
/// Set the body of a response to a given string builder.
///
/// You likely want to also set the request `content-type` header to an
/// appropriate value for the format of the content.
///
/// # Examples
///
/// ```gleam
/// let body =
/// response(201)
/// |> string_builder_body("Hello, Joe!")
/// // -> Response(
/// // 201,
/// // [],
/// // Text(string_builder.from_string("Hello, Joe"))
/// // )
/// ```
///
pub fn string_body(response: Response, content: String) -> Response {
response
|> response.set_body(Text(string_builder.from_string(content)))
}
/// Escape a string so that it can be safely included in a HTML document.
///
/// Any content provided by the user should be escaped before being included in
/// a HTML document to prevent cross-site scripting attacks.
///
/// # Examples
///
/// ```gleam
/// escape_html("<h1>Hello, Joe!</h1>")
/// // -> "<h1>Hello, Joe!</h1>"
/// ```
///
pub fn escape_html(content: String) -> String {
do_escape_html("", content)
}
fn do_escape_html(escaped: String, content: String) -> String {
case string.pop_grapheme(content) {
Ok(#("<", xs)) -> do_escape_html(escaped <> "<", xs)
Ok(#(">", xs)) -> do_escape_html(escaped <> ">", xs)
Ok(#("&", xs)) -> do_escape_html(escaped <> "&", xs)
Ok(#(x, xs)) -> do_escape_html(escaped <> x, xs)
Error(_) -> escaped <> content
}
}
/// Create an empty response with status code 405: Method Not Allowed. Use this
/// when a request does not have an appropriate method to be handled.
///
/// The `allow` header will be set to a comma separated list of the permitted
/// methods.
///
/// # Examples
///
/// ```gleam
/// method_not_allowed(allowed: [Get, Post])
/// // -> Response(405, [#("allow", "GET, POST")], Empty)
/// ```
///
pub fn method_not_allowed(allowed methods: List(Method)) -> Response {
let allowed =
methods
|> list.map(http.method_to_string)
|> list.sort(string.compare)
|> string.join(", ")
|> string.uppercase
HttpResponse(405, [#("allow", allowed)], Empty)
}
/// Create an empty response with status code 200: OK.
///
/// # Examples
///
/// ```gleam
/// ok()
/// // -> Response(200, [], Empty)
/// ```
///
pub fn ok() -> Response {
HttpResponse(200, [], Empty)
}
/// Create an empty response with status code 201: Created.
///
/// # Examples
///
/// ```gleam
/// created()
/// // -> Response(201, [], Empty)
/// ```
///
pub fn created() -> Response {
HttpResponse(201, [], Empty)
}
/// Create an empty response with status code 202: Accepted.
///
/// # Examples
///
/// ```gleam
/// accepted()
/// // -> Response(202, [], Empty)
/// ```
///
pub fn accepted() -> Response {
HttpResponse(202, [], Empty)
}
/// Create an empty response with status code 303: See Other, and the `location`
/// header set to the given URL. Used to redirect the client to another page.
///
/// # Examples
///
/// ```gleam
/// redirect(to: "https://example.com")
/// // -> Response(303, [#("location", "https://example.com")], Empty)
/// ```
///
pub fn redirect(to url: String) -> Response {
HttpResponse(303, [#("location", url)], Empty)
}
/// Create an empty response with status code 308: Moved Permanently, and the
/// `location` header set to the given URL. Used to redirect the client to
/// another page.
///
/// This redirect is permanent and the client is expected to cache the new
/// location, using it for future requests.
///
/// # Examples
///
/// ```gleam
/// moved_permanently(to: "https://example.com")
/// // -> Response(308, [#("location", "https://example.com")], Empty)
/// ```
///
pub fn moved_permanently(to url: String) -> Response {
HttpResponse(308, [#("location", url)], Empty)
}
/// Create an empty response with status code 204: No content.
///
/// # Examples
///
/// ```gleam
/// no_content()
/// // -> Response(204, [], Empty)
/// ```
///
pub fn no_content() -> Response {
HttpResponse(204, [], Empty)
}
/// Create an empty response with status code 404: No content.
///
/// # Examples
///
/// ```gleam
/// not_found()
/// // -> Response(404, [], Empty)
/// ```
///
pub fn not_found() -> Response {
HttpResponse(404, [], Empty)
}
/// Create an empty response with status code 400: Bad request.
///
/// # Examples
///
/// ```gleam
/// bad_request()
/// // -> Response(400, [], Empty)
/// ```
///
pub fn bad_request() -> Response {
HttpResponse(400, [], Empty)
}
/// Create an empty response with status code 413: Entity too large.
///
/// # Examples
///
/// ```gleam
/// entity_too_large()
/// // -> Response(413, [], Empty)
/// ```
///
pub fn entity_too_large() -> Response {
HttpResponse(413, [], Empty)
}
/// Create an empty response with status code 415: Unsupported media type.
///
/// The `allow` header will be set to a comma separated list of the permitted
/// content-types.
///
/// # Examples
///
/// ```gleam
/// unsupported_media_type(accept: ["application/json", "text/plain"])
/// // -> Response(415, [#("allow", "application/json, text/plain")], Empty)
/// ```
///
pub fn unsupported_media_type(accept acceptable: List(String)) -> Response {
let acceptable = string.join(acceptable, ", ")
HttpResponse(415, [#("accept", acceptable)], Empty)
}
/// Create an empty response with status code 422: Unprocessable entity.
///
/// # Examples
///
/// ```gleam
/// unprocessable_entity()
/// // -> Response(422, [], Empty)
/// ```
///
pub fn unprocessable_entity() -> Response {
HttpResponse(422, [], Empty)
}
/// Create an empty response with status code 500: Internal server error.
///
/// # Examples
///
/// ```gleam
/// internal_server_error()
/// // -> Response(500, [], Empty)
/// ```
///
pub fn internal_server_error() -> Response {
HttpResponse(500, [], Empty)
}
//
// Requests
//
/// The connection to the client for a HTTP request.
///
/// The body of the request can be read from this connection using functions
/// such as `require_multipart_body`.
///
pub opaque type Connection {
Connection(
reader: Reader,
max_body_size: Int,
max_files_size: Int,
read_chunk_size: Int,
secret_key_base: String,
temporary_directory: String,
)
}
fn make_connection(body_reader: Reader, secret_key_base: String) -> Connection {
// TODO: replace `/tmp` with appropriate for the OS
let prefix = "/tmp/gleam-wisp/"
let temporary_directory = join_path(prefix, random_slug())
Connection(
reader: body_reader,
max_body_size: 8_000_000,
max_files_size: 32_000_000,
read_chunk_size: 1_000_000,
temporary_directory: temporary_directory,
secret_key_base: secret_key_base,
)
}
type BufferedReader {
BufferedReader(reader: Reader, buffer: BitArray)
}
type Quotas {
Quotas(body: Int, files: Int)
}
fn decrement_body_quota(quotas: Quotas, size: Int) -> Result(Quotas, Response) {
let quotas = Quotas(..quotas, body: quotas.body - size)
case quotas.body < 0 {
True -> Error(entity_too_large())
False -> Ok(quotas)
}
}
fn decrement_quota(quota: Int, size: Int) -> Result(Int, Response) {
case quota - size {
quota if quota < 0 -> Error(entity_too_large())
quota -> Ok(quota)
}
}
fn buffered_read(reader: BufferedReader, chunk_size: Int) -> Result(Read, Nil) {
case reader.buffer {
<<>> -> reader.reader(chunk_size)
_ -> Ok(Chunk(reader.buffer, reader.reader))
}
}
type Reader =
fn(Int) -> Result(Read, Nil)
type Read {
Chunk(BitArray, next: Reader)
ReadingFinished
}
/// Set the maximum permitted size of a request body of the request in bytes.
///
/// If a body is larger than this size attempting to read the body will result
/// in a response with status code 413: Entity too large will be returned to the
/// client.
///
/// This limit only applies for headers and bodies that get read into memory.
/// Part of a multipart body that contain files and so are streamed to disc
/// instead use the `max_files_size` limit.
///
pub fn set_max_body_size(request: Request, size: Int) -> Request {
Connection(..request.body, max_body_size: size)
|> request.set_body(request, _)
}
/// Get the maximum permitted size of a request body of the request in bytes.
///
pub fn get_max_body_size(request: Request) -> Int {
request.body.max_body_size
}
/// Set the secret key base used to sign cookies and other sensitive data.
///
/// This key must be at least 64 bytes long and should be kept secret. Anyone
/// with this secret will be able to manipulate signed cookies and other sensitive
/// data.
///
/// # Panics
///
/// This function will panic if the key is less than 64 bytes long.
///
pub fn set_secret_key_base(request: Request, key: String) -> Request {
case string.byte_size(key) < 64 {
True -> panic as "Secret key base must be at least 64 bytes long"
False ->
Connection(..request.body, secret_key_base: key)
|> request.set_body(request, _)
}
}
/// Get the secret key base used to sign cookies and other sensitive data.
///
pub fn get_secret_key_base(request: Request) -> String {
request.body.secret_key_base
}
/// Set the maximum permitted size of all files uploaded by a request, in bytes.
///
/// If a request contains fails which are larger in total than this size
/// then attempting to read the body will result in a response with status code
/// 413: Entity too large will be returned to the client.
///
/// This limit only applies for files in a multipart body that get streamed to
/// disc. For headers and other content that gets read into memory use the
/// `max_files_size` limit.
///
pub fn set_max_files_size(request: Request, size: Int) -> Request {
Connection(..request.body, max_files_size: size)
|> request.set_body(request, _)
}
/// Get the maximum permitted total size of a files uploaded by a request in
/// bytes.
///
pub fn get_max_files_size(request: Request) -> Int {
request.body.max_files_size
}
/// The the size limit for each chunk of the request body when read from the
/// client.
///
/// This value is passed to the underlying web server when reading the body and
/// the exact size of chunks read depends on the server implementation. It most
/// likely will read chunks smaller than this size if not yet enough data has
/// been received from the client.
///
pub fn set_read_chunk_size(request: Request, size: Int) -> Request {
Connection(..request.body, read_chunk_size: size)
|> request.set_body(request, _)
}
/// Get the size limit for each chunk of the request body when read from the
/// client.
///
pub fn get_read_chunk_size(request: Request) -> Int {
request.body.read_chunk_size
}
/// A convenient alias for a HTTP request with a Wisp connection as the body.
///
pub type Request =
HttpRequest(Connection)
/// This middleware function ensures that the request has a specific HTTP
/// method, returning an empty response with status code 405: Method not allowed
/// if the method is not correct.
///
/// # Examples
///
/// ```gleam
/// fn handle_request(request: Request) -> Response {
/// use <- wisp.require_method(request, http.Patch)
/// // ...
/// }
/// ```
///
pub fn require_method(
request: HttpRequest(t),
method: Method,
next: fn() -> Response,
) -> Response {
case request.method == method {
True -> next()
False -> method_not_allowed(allowed: [method])
}
}
// TODO: re-export once Gleam has a syntax for that
/// Return the non-empty segments of a request path.
///
/// # Examples
///
/// ```gleam
/// > request.new()
/// > |> request.set_path("/one/two/three")
/// > |> wisp.path_segments
/// ["one", "two", "three"]
/// ```
///
pub const path_segments = request.path_segments
// TODO: re-export once Gleam has a syntax for that
/// Set a given header to a given value, replacing any existing value.
///
/// # Examples
///
/// ```gleam
/// > wisp.ok()
/// > |> wisp.set_header("content-type", "application/json")
/// Request(200, [#("content-type", "application/json")], Empty)
/// ```
///
pub const set_header = response.set_header
/// Parse the query parameters of a request into a list of key-value pairs. The
/// `key_find` function in the `gleam/list` stdlib module may be useful for
/// finding values in the list.
///
/// Query parameter names do not have to be unique and so may appear multiple
/// times in the list.
///
pub fn get_query(request: Request) -> List(#(String, String)) {
request.get_query(request)
|> result.unwrap([])
}
/// This function overrides an incoming POST request with a method given in
/// the request's `_method` query paramerter. This is useful as web browsers
/// typically only support GET and POST requests, but our application may
/// expect other HTTP methods that are more semantically correct.
///
/// The methods PUT, PATCH, and DELETE are accepted for overriding, all others
/// are ignored.
///
/// The `_method` query paramerter can be specified in a HTML form like so:
///
/// <form method="POST" action="/item/1?_method=DELETE">
/// <button type="submit">Delete item</button>
/// </form>
///
/// # Examples
///
/// ```gleam
/// fn handle_request(request: Request) -> Response {
/// let request = wisp.method_override(request)
/// // The method has now been overridden if appropriate
/// }
/// ```
///
pub fn method_override(request: HttpRequest(a)) -> HttpRequest(a) {
use <- bool.guard(when: request.method != http.Post, return: request)
{
use query <- result.try(request.get_query(request))
use value <- result.try(list.key_find(query, "_method"))
use method <- result.map(http.parse_method(value))
case method {
http.Put | http.Patch | http.Delete -> request.set_method(request, method)
_ -> request
}
}
|> result.unwrap(request)
}
// TODO: don't always return entity too large. Other errors are possible, such as
// network errors.
/// A middleware function which reads the entire body of the request as a string.
///
/// This function does not cache the body in any way, so if you call this
/// function (or any other body reading function) more than once it may hang or
/// return an incorrect value, depending on the underlying web server. It is the
/// responsibility of the caller to cache the body if it is needed multiple
/// times.
///
/// If the body is larger than the `max_body_size` limit then an empty response
/// with status code 413: Entity too large will be returned to the client.
///
/// If the body is found not to be valid UTF-8 then an empty response with
/// status code 400: Bad request will be returned to the client.
///
/// # Examples
///
/// ```gleam
/// fn handle_request(request: Request) -> Response {
/// use body <- wisp.require_string_body(request)
/// // ...
/// }
/// ```
///
pub fn require_string_body(
request: Request,
next: fn(String) -> Response,
) -> Response {
case read_body_to_bitstring(request) {
Ok(body) -> or_400(bit_array.to_string(body), next)
Error(_) -> entity_too_large()
}
}
// TODO: don't always return entity too large. Other errors are possible, such as
// network errors.
/// A middleware function which reads the entire body of the request as a bit
/// string.
///
/// This function does not cache the body in any way, so if you call this
/// function (or any other body reading function) more than once it may hang or
/// return an incorrect value, depending on the underlying web server. It is the
/// responsibility of the caller to cache the body if it is needed multiple
/// times.
///
/// If the body is larger than the `max_body_size` limit then an empty response
/// with status code 413: Entity too large will be returned to the client.
///
/// # Examples
///
/// ```gleam
/// fn handle_request(request: Request) -> Response {
/// use body <- wisp.require_string_body(request)
/// // ...
/// }
/// ```
///
pub fn require_bit_array_body(
request: Request,
next: fn(BitArray) -> Response,
) -> Response {
case read_body_to_bitstring(request) {
Ok(body) -> next(body)
Error(_) -> entity_too_large()
}
}
// TODO: don't always return entity to large. Other errors are possible, such as
// network errors.
/// Read the entire body of the request as a bit string.
///
/// You may instead wish to use the `require_bit_array_body` or the
/// `require_string_body` middleware functions instead.
///
/// This function does not cache the body in any way, so if you call this
/// function (or any other body reading function) more than once it may hang or
/// return an incorrect value, depending on the underlying web server. It is the
/// responsibility of the caller to cache the body if it is needed multiple
/// times.
///
/// If the body is larger than the `max_body_size` limit then an empty response
/// with status code 413: Entity too large will be returned to the client.
///
pub fn read_body_to_bitstring(request: Request) -> Result(BitArray, Nil) {
let connection = request.body
read_body_loop(
connection.reader,
connection.read_chunk_size,
connection.max_body_size,
<<>>,
)
}
fn read_body_loop(
reader: Reader,
read_chunk_size: Int,
max_body_size: Int,
accumulator: BitArray,
) -> Result(BitArray, Nil) {
use chunk <- result.try(reader(read_chunk_size))
case chunk {
ReadingFinished -> Ok(accumulator)
Chunk(chunk, next) -> {
let accumulator = bit_array.append(accumulator, chunk)
case bit_array.byte_size(accumulator) > max_body_size {
True -> Error(Nil)
False ->
read_body_loop(next, read_chunk_size, max_body_size, accumulator)
}
}
}
}
/// A middleware which extracts form data from the body of a request that is
/// encoded as either `application/x-www-form-urlencoded` or
/// `multipart/form-data`.
///
/// Extracted fields are sorted into alphabetical order by key, so if you wish
/// to use pattern matching the order can be relied upon.
///
/// ```gleam
/// fn handle_request(request: Request) -> Response {
/// use form <- wisp.require_form(request)
/// case form.values {
/// [#("password", pass), #("username", username)] -> // ...
/// _ -> // ...
/// }
/// }
/// ```
///
/// The `set_max_body_size`, `set_max_files_size`, and `set_read_chunk_size` can
/// be used to configure the reading of the request body.
///
/// Any file uploads will streamed into temporary files on disc. These files are
/// automatically deleted when the request handler returns, so if you wish to
/// use them after the request has completed you will need to move them to a new
/// location.
///
/// If the request does not have a recognised `content-type` header then an
/// empty response with status code 415: Unsupported media type will be returned
/// to the client.
///
/// If the request body is larger than the `max_body_size` or `max_files_size`