ic_http_certification/http/http_response.rs
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
use crate::HeaderField;
use candid::{
types::{Serializer, Type, TypeInner},
CandidType, Deserialize,
};
pub use http::StatusCode;
use serde::Deserializer;
use std::{borrow::Cow, fmt::Debug};
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct StatusCodeWrapper(StatusCode);
impl CandidType for StatusCodeWrapper {
fn _ty() -> Type {
TypeInner::Nat16.into()
}
fn idl_serialize<S>(&self, serializer: S) -> Result<(), S::Error>
where
S: Serializer,
{
self.0.as_u16().idl_serialize(serializer)
}
}
impl<'de> Deserialize<'de> for StatusCodeWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
u16::deserialize(deserializer).and_then(|status_code| {
StatusCode::from_u16(status_code)
.map(Into::into)
.map_err(|_| serde::de::Error::custom("Invalid HTTP Status Code."))
})
}
}
impl From<StatusCode> for StatusCodeWrapper {
fn from(status_code: StatusCode) -> Self {
Self(status_code)
}
}
/// A Candid-encodable representation of an HTTP response. This struct is used
/// by the `http_request` method of the HTTP Gateway Protocol's Candid interface.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .with_upgrade(false)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// assert_eq!(response.upgrade(), Some(false));
/// ```
///
/// # Helpers
///
/// There are also a number of convenience methods for quickly creating an [HttpResponse] with
/// commonly used HTTP status codes:
///
/// - [OK](HttpResponse::ok)
/// - [CREATED](HttpResponse::created)
/// - [NO_CONTENT](HttpResponse::no_content)
/// - [MOVED_PERMANENTLY](HttpResponse::moved_permanently)
/// - [TEMPORARY_REDIRECT](HttpResponse::temporary_redirect)
/// - [BAD_REQUEST](HttpResponse::bad_request)
/// - [UNAUTHORIZED](HttpResponse::unauthorized)
/// - [FORBIDDEN](HttpResponse::forbidden)
/// - [NOT_FOUND](HttpResponse::not_found)
/// - [METHOD_NOT_ALLOWED](HttpResponse::method_not_allowed)
/// - [TOO_MANY_REQUESTS](HttpResponse::too_many_requests)
/// - [INTERNAL_SERVER_ERROR](HttpResponse::internal_server_error)
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::ok(b"Hello, World!", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// ```
#[derive(Clone, CandidType, Deserialize)]
pub struct HttpResponse<'a> {
/// HTTP response status code.
status_code: StatusCodeWrapper,
/// HTTP response headers.
headers: Vec<HeaderField>,
/// HTTP response body as an array of bytes.
body: Cow<'a, [u8]>,
/// Whether the corresponding HTTP request should be upgraded to an update
/// call.
upgrade: Option<bool>,
}
impl<'a> HttpResponse<'a> {
/// Creates a new [HttpResponseBuilder] initialized with an OK status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::ok(b"Hello, World!", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// ```
pub fn ok(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::OK)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a CREATED status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::created(b"Hello, World!", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::CREATED);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// ```
pub fn created(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::CREATED)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a NO_CONTENT status code and
/// the given headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::no_content(vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::NO_CONTENT);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// ```
pub fn no_content(headers: Vec<(String, String)>) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::NO_CONTENT)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a MOVED_PERMANENTLY status code and
/// the given location and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::moved_permanently("https://www.example.com", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::MOVED_PERMANENTLY);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into()), ("Location".into(), "https://www.example.com".into())]);
/// ```
pub fn moved_permanently(
location: impl Into<String>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
let headers = headers
.into_iter()
.chain(std::iter::once(("Location".into(), location.into())))
.collect();
Self::builder()
.with_status_code(StatusCode::MOVED_PERMANENTLY)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a NOT_MODIFIED status code and
/// the given headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::not_modified(vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::NOT_MODIFIED);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// ```
pub fn not_modified(headers: Vec<(String, String)>) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::NOT_MODIFIED)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a TEMPORARY_REDIRECT status code and
/// the given location and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::temporary_redirect("https://www.example.com", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::TEMPORARY_REDIRECT);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into()), ("Location".into(), "https://www.example.com".into())]);
/// ```
pub fn temporary_redirect(
location: impl Into<String>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
let headers = headers
.into_iter()
.chain(std::iter::once(("Location".into(), location.into())))
.collect();
Self::builder()
.with_status_code(StatusCode::TEMPORARY_REDIRECT)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a BAD_REQUEST status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::bad_request(b"Bad Request", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::BAD_REQUEST);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Bad Request");
/// ```
pub fn bad_request(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::BAD_REQUEST)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with an UNAUTHORIZED status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::unauthorized(b"Unauthorized", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::UNAUTHORIZED);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Unauthorized");
/// ```
pub fn unauthorized(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::UNAUTHORIZED)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a FORBIDDEN status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::forbidden(b"Forbidden", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::FORBIDDEN);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Forbidden");
/// ```
pub fn forbidden(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::FORBIDDEN)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a NOT_FOUND status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::not_found(b"Not Found", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::NOT_FOUND);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Not Found");
/// ```
pub fn not_found(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::NOT_FOUND)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a METHOD_NOT_ALLOWED status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::method_not_allowed(b"Method Not Allowed", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::METHOD_NOT_ALLOWED);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Method Not Allowed");
/// ```
pub fn method_not_allowed(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::METHOD_NOT_ALLOWED)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a CONFLICT status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::too_many_requests(b"Too many requests", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::TOO_MANY_REQUESTS);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Too many requests");
/// ```
pub fn too_many_requests(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::TOO_MANY_REQUESTS)
.with_body(body)
.with_headers(headers)
}
/// Creates a new [HttpResponseBuilder] initialized with a INTERNAL_SERVER_ERROR status code and
/// the given body and headers.
///
/// This method returns an instance of [HttpResponseBuilder] that can be used to
/// to create an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::internal_server_error(b"Internal Server Error", vec![("Content-Type".into(), "text/plain".into())]).build();
///
/// assert_eq!(response.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Internal Server Error");
/// ```
pub fn internal_server_error(
body: impl Into<Cow<'a, [u8]>>,
headers: Vec<(String, String)>,
) -> HttpResponseBuilder<'a> {
Self::builder()
.with_status_code(StatusCode::INTERNAL_SERVER_ERROR)
.with_body(body)
.with_headers(headers)
}
/// Creates and returns an instance of [HttpResponseBuilder], a builder-style
/// object that can be used to construct an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .with_upgrade(false)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// assert_eq!(response.upgrade(), Some(false));
/// ```
#[inline]
pub fn builder() -> HttpResponseBuilder<'a> {
HttpResponseBuilder::new()
}
/// Returns the HTTP status code of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// ```
#[inline]
pub fn status_code(&self) -> StatusCode {
self.status_code.0
}
/// Returns the HTTP headers of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build();
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// ```
#[inline]
pub fn headers(&self) -> &[HeaderField] {
&self.headers
}
/// Returns a mutable reference to the HTTP headers of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let mut response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build();
///
/// response.headers_mut().push(("Content-Length".into(), "13".into()));
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into()), ("Content-Length".into(), "13".into())]);
/// ```
#[inline]
pub fn headers_mut(&mut self) -> &mut Vec<HeaderField> {
&mut self.headers
}
/// Adds an additional header to the HTTP response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let mut response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build();
///
/// response.add_header(("Content-Length".into(), "13".into()));
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into()), ("Content-Length".into(), "13".into())]);
/// ```
#[inline]
pub fn add_header(&mut self, header: HeaderField) {
self.headers.push(header);
}
/// Returns the HTTP body of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_body(b"Hello, World!")
/// .build();
///
/// assert_eq!(response.body(), b"Hello, World!");
/// ```
#[inline]
pub fn body(&self) -> &[u8] {
&self.body
}
/// Returns the upgrade flag of the response. This will determine if the HTTP Gateway will
/// upgrade the request to an update call.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_upgrade(true)
/// .build();
///
/// assert_eq!(response.upgrade(), Some(true));
/// ```
#[inline]
pub fn upgrade(&self) -> Option<bool> {
self.upgrade
}
}
/// An HTTP response builder.
///
/// This type can be used to construct an instance of an [HttpResponse] using a builder-like
/// pattern.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .with_upgrade(false)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// assert_eq!(response.upgrade(), Some(false));
/// ```
#[derive(Debug, Clone, Default)]
pub struct HttpResponseBuilder<'a> {
status_code: Option<StatusCodeWrapper>,
headers: Vec<HeaderField>,
body: Cow<'a, [u8]>,
upgrade: Option<bool>,
}
impl<'a> HttpResponseBuilder<'a> {
/// Creates a new instance of the [HttpResponseBuilder] that can be used to
/// constract an [HttpResponse].
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .with_upgrade(false)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// assert_eq!(response.upgrade(), Some(false));
/// ```
pub fn new() -> Self {
Self::default()
}
/// Sets the status code of the HTTP response.
///
/// By default, the status code will be set to `200`.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// ```
pub fn with_status_code(mut self, status_code: StatusCode) -> Self {
self.status_code = Some(status_code.into());
self
}
/// Sets the headers of the HTTP response.
///
/// By default, the headers will be set to an empty array.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build();
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// ```
pub fn with_headers(mut self, headers: Vec<HeaderField>) -> Self {
self.headers = headers;
self
}
/// Sets the body of the HTTP response.
///
/// This function will accept both owned and borrowed values. By default,
/// the body will be set to an empty array.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_body(b"Hello, World!")
/// .build();
///
/// assert_eq!(response.body(), b"Hello, World!");
/// ```
pub fn with_body(mut self, body: impl Into<Cow<'a, [u8]>>) -> Self {
self.body = body.into();
self
}
/// Sets the upgrade flag of the HTTP response. This will determine if the HTTP Gateway will
/// upgrade the request to an update call.
///
/// By default, the upgrade flag will be set to `None`, which is the same as `Some(false)`.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_upgrade(true)
/// .build();
///
/// assert_eq!(response.upgrade(), Some(true));
/// ```
pub fn with_upgrade(mut self, upgrade: bool) -> Self {
self.upgrade = Some(upgrade);
self
}
/// Build an [HttpResponse] from the builder.
///
/// If the status code is not set, it will default to `200`.
/// If the upgrade flag is not set, it will default to `None`.
/// If the headers or body are not set, they will default to empty arrays.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .with_upgrade(false)
/// .build();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(response.body(), b"Hello, World!");
/// assert_eq!(response.upgrade(), Some(false));
/// ```
pub fn build(self) -> HttpResponse<'a> {
HttpResponse {
status_code: self.status_code.unwrap_or(StatusCode::OK.into()),
headers: self.headers,
body: self.body,
upgrade: self.upgrade,
}
}
/// Build an [HttpUpdateResponse] from the builder.
///
/// If the status code is not set, it will default to `200`.
/// If the headers or body are not set, they will default to empty arrays.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, HttpUpdateResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .build();
///
/// let update_response = HttpUpdateResponse::from(response);
///
/// assert_eq!(update_response.status_code(), StatusCode::OK);
/// assert_eq!(update_response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(update_response.body(), b"Hello, World!");
/// ```
pub fn build_update(self) -> HttpUpdateResponse<'a> {
HttpUpdateResponse {
status_code: self.status_code.unwrap_or(StatusCode::OK.into()),
headers: self.headers,
body: self.body,
}
}
}
impl<'a> From<HttpResponse<'a>> for HttpResponseBuilder<'a> {
fn from(response: HttpResponse<'a>) -> Self {
Self {
status_code: Some(response.status_code),
headers: response.headers,
body: response.body,
upgrade: response.upgrade,
}
}
}
impl PartialEq for HttpResponse<'_> {
fn eq(&self, other: &Self) -> bool {
let mut a_headers = self.headers().to_vec();
a_headers.sort();
let mut b_headers = other.headers().to_vec();
b_headers.sort();
self.status_code == other.status_code
&& a_headers == b_headers
&& self.body == other.body
&& self.upgrade == other.upgrade
}
}
impl Debug for HttpResponse<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Truncate body to 100 characters for debug output
let max_body_len = 100;
let formatted_body = if self.body.len() > max_body_len {
format!("{:?}...", &self.body[..max_body_len])
} else {
format!("{:?}", &self.body)
};
f.debug_struct("HttpResponse")
.field("status_code", &self.status_code)
.field("headers", &self.headers)
.field("body", &formatted_body)
.field("upgrade", &self.upgrade)
.finish()
}
}
/// A Candid-encodable representation of an HTTP update response. This struct is used
/// by the `http_update_request` method of the HTTP Gateway Protocol.
///
/// This is the same as [HttpResponse], excluding the
/// [upgrade](HttpResponse::upgrade) field.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, HttpUpdateResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .with_body(b"Hello, World!")
/// .build_update();
///
/// let update_response = HttpUpdateResponse::from(response);
///
/// assert_eq!(update_response.status_code(), StatusCode::OK);
/// assert_eq!(update_response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// assert_eq!(update_response.body(), b"Hello, World!");
/// ```
#[derive(Clone, Debug, CandidType, Deserialize, PartialEq, Eq)]
pub struct HttpUpdateResponse<'a> {
/// HTTP response status code.
status_code: StatusCodeWrapper,
/// HTTP response headers.
headers: Vec<HeaderField>,
/// HTTP response body as an array of bytes.
body: Cow<'a, [u8]>,
}
impl<'a> HttpUpdateResponse<'a> {
/// Returns the HTTP status code of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::{HttpResponse, StatusCode};
///
/// let response = HttpResponse::builder()
/// .with_status_code(StatusCode::OK)
/// .build_update();
///
/// assert_eq!(response.status_code(), StatusCode::OK);
/// ```
#[inline]
pub fn status_code(&self) -> StatusCode {
self.status_code.0
}
/// Returns the HTTP headers of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build_update();
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into())]);
/// ```
#[inline]
pub fn headers(&self) -> &[HeaderField] {
&self.headers
}
/// Returns a mutable reference to the HTTP headers of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let mut response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build_update();
///
/// response.headers_mut().push(("Content-Length".into(), "13".into()));
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into()), ("Content-Length".into(), "13".into())]);
/// ```
#[inline]
pub fn headers_mut(&mut self) -> &mut Vec<HeaderField> {
&mut self.headers
}
/// Adds an additional header to the HTTP response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let mut response = HttpResponse::builder()
/// .with_headers(vec![("Content-Type".into(), "text/plain".into())])
/// .build_update();
///
/// response.add_header(("Content-Length".into(), "13".into()));
///
/// assert_eq!(response.headers(), &[("Content-Type".into(), "text/plain".into()), ("Content-Length".into(), "13".into())]);
/// ```
#[inline]
pub fn add_header(&mut self, header: HeaderField) {
self.headers.push(header);
}
/// Returns the HTTP body of the response.
///
/// # Examples
///
/// ```
/// use ic_http_certification::HttpResponse;
///
/// let response = HttpResponse::builder()
/// .with_body(b"Hello, World!")
/// .build_update();
///
/// assert_eq!(response.body(), b"Hello, World!");
/// ```
#[inline]
pub fn body(&self) -> &[u8] {
&self.body
}
}
impl<'a> From<HttpResponse<'a>> for HttpUpdateResponse<'a> {
fn from(response: HttpResponse<'a>) -> Self {
Self {
status_code: response.status_code,
headers: response.headers,
body: response.body,
}
}
}