107 KiB
Version 0.5.1 (May 22, 2024)
This release contains the following crate updates:
rocket0.5.1rocket_db_pools0.2.0rocket_dyn_templates0.2.0rocket_ws0.1.1
rocket 0.5.1
-
The following
charandstd::ops::Rangetypes now implementFromForm:charRange<T: FromForm>withstartandendfieldsRangeFrom<T: FromForm>withstartfieldRangeTo<T: FromForm>withendfieldRangeToInclusive<T: FromForm>withendfield
-
[T; N],Vec<T>, and[u8]can now be passed touri!. -
The guide now includes a deploying section.
-
The
FromFormderive now properly records errors involving entire forms. -
FromFormderive can now be used in code emitted bymacro_rules!macros. -
(fix #2668 via 52de9a)
TempFilenow ensures it flushes before being persisted.
rocket_db_pools 0.2.0
-
SQLite extensions are now supported in
sqlx_sqlite.Use a database configuration option of
extensionsto specify extensions:[default.databases.db_name] url = "db.sqlite" # This option is only supported by the `sqlx_sqlite` driver. extensions = ["memvfs", "rot13"] -
(breaking)
deadpoolwas updated to0.13. -
(breaking) The
Configstructure has a newextensionsfield.
rocket_dyn_templates 0.2.0
-
Support for
minijinja2.0templates was introduced.Templates with an extension of
.j2are recognized and rendered with Minijinja. -
(breaking)
handlebarswas updated to5.1.
rocket_ws 0.1.1
-
Introduced
WebSocket::accept_key()method. -
tungstenitewas updated to0.21.
General Changes
-
The
rust-versionfor all crates was updated to1.64.This reflects the correct MSRV required to build
rocket0.5.0. -
License files are now present in all published crates.
Version 0.5.0 (Nov 17, 2023)
Major Features and Improvements
This release introduces the following major features and improvements:
- Support for compilation on Rust's stable release channel.
- A rewritten, fully asynchronous core with support for
async/await. - WebSocket support via
rocket_ws. - Feature-complete forms support including multipart, collections, ad-hoc validation, and context.
- Sentinels: automatic verification of application state at start-up to prevent runtime errors.
- Graceful shutdown with configurable signaling, grace periods, notification, and shutdown fairings.
- An entirely new, flexible and robust configuration system based on Figment.
- Typed asynchronous streams and Server-Sent Events with generator syntax.
- Asynchronous database pooling support via
rocket_db_pools. - Support for mutual TLS and client
Certificates. - Automatic support for HTTP/2 including
h2ALPN. - Graduation of
json,msgpack, anduuidrocket_contribfeatures into core. - An automatically enabled
Shield: security and privacy headers for all responses. - Type-system enforced incoming data limits to mitigate memory-based DoS attacks.
- Compile-time URI literals via a fully revamped
uri!macro. - Request connection upgrade APIs with support for raw I/O with the client.
- Full support for UTF-8 characters in routes and catchers.
- Precise detection of missing managed state, databases, and templating with sentinels.
- Typed build phases with strict application-level guarantees.
- Ignorable segments: wildcard route matching with no typing restrictions.
- First-class support for
serdefor built-in guards and types. - New application launch attributes:
#[launch]and#[rocket::main]. - Default catchers via
#[catch(default)], which handle any status code. - Catcher scoping to narrow the scope of a catcher to a URI prefix.
- Built-in libraries and support for asynchronous testing.
- A
TempFiledata and form guard for automatic uploading to a temporary file. - A
Capped<T>data and form guard which enables detecting truncation due to data limits. - Support for dynamic and static prefixing and suffixing of route URIs in
uri!. - Support for custom config profiles and automatic typed config extraction.
- Rewritten, zero-copy, RFC compliant URI parsers with support for URI-
References. - Multi-segment parameters (
<param..>) which match zero segments. - A
local_cache!macro for request-local storage of non-uniquely typed values. - A
CookieJarwithout "one-at-a-time" limitations. - Singleton fairings with replacement and guaranteed uniqueness.
- Data limit declaration in SI units: "2 MiB",
2.mebibytes(). - Optimistic responding even when data is left unread or limits are exceeded.
- Fully decoded borrowed strings as dynamic parameters, form and data guards.
- Borrowed byte slices as data and form guards.
- Fail-fast behavior for misconfigured secrets, file serving paths.
- Support for generics and custom generic bounds in
#[derive(Responder)]. - Default ranking colors, which prevent more routing collisions automatically.
- Improved error logging with suggestions when common errors are detected.
- Completely rewritten examples including a new real-time
chatapplication.
Support for Rust Stable
As a result of support for Rust stable (Rust 2021 Edition and beyond),
#![feature(..)] crate attributes are no longer required to use Rocket. The
complete canonical example with a single hello route becomes:
#[macro_use] extern crate rocket;
#[get("/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
format!("Hello, {} year old named {}!", age, name)
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/hello", routes![hello])
}
See a diff of the changes from v0.4.
- #![feature(proc_macro_hygiene, decl_macro)]
-
#[macro_use] extern crate rocket;
#[get("/<name>/<age>")]
- fn hello(name: String, age: u8) -> String {
+ fn hello(name: &str, age: u8) -> String {
format!("Hello, {} year old named {}!", age, name)
}
- fn main() {
- rocket::ignite().mount("/hello", routes![hello]).launch();
- }
+ #[launch]
+ fn rocket() -> _ {
+ rocket::build().mount("/hello", routes![hello])
+ }
Breaking Changes
This release includes many breaking changes. For a walkthrough guide on handling these changes, see the v0.4 to v0.5 migration guide. The most significant changes are listed below.
Silent Changes
These changes are invisible to the compiler and will not yield errors or warnings at compile-time. We strongly advise all application authors to review this list carefully.
- Blocking I/O (long running compute, synchronous
sleep(),Mutex,RwLock, etc.) may prevent the server from making progress and should be avoided, replaced with anasyncvariant, or performed in a worker thread. This is a consequence of Rust's cooperativeasyncmultitasking. For details, see the new multitasking section of the guide. ROCKET_ENVis nowROCKET_PROFILE. A warning is emitted a launch time if the former is set.- The default profile for debug builds is now
debug, notdev. - The default profile for release builds is now
release, notprod. ROCKET_LOGis nowROCKET_LOG_LEVEL. A warning is emitted a launch time if the former is set.ROCKET_ADDRESSaccepts only IP addresses, no longer resolves hostnames likelocalhost.ROCKET_CLI_COLORSaccepts booleanstrue,falsein place of strings"on","off".- It is a launch-time error if
secretsis enabled in non-debugprofiles without a configuredsecret_key. - A misconfigured
template_diris reported as an error at launch time. FileServer::new()fails immediately if the provided directory does not exist.- Catcher collisions result in a launch failure as opposed to a warning.
- Default ranks now range from
-12to-1. There is no breaking change if only code generated routes are used. Manually configured routes with negative ranks may collide or be considered in a different order than before. - The order of execution of path and query guards relative to each other is now unspecified.
- URIs beginning with
:are properly recognized as invalid and rejected. - URI normalization now normalizes the query part as well.
- The
Segmentsiterator now returns percent-decoded&strs. - Forms are now parsed leniently by the
Formguard. UseStrictfor the previous behavior. - The
Option<T>form guard defaults toNoneinstead of the default value forT. - When data limits are exceeded, a
413 Payload Too Largestatus is returned to the client. - The default catcher now returns JSON when the client indicates preference via the
Acceptheader. - Empty boolean form values parse as
true: the query string?fis the same as?f=true. Created<R>does not automatically send anETagheader ifR: Hash. UseCreated::tagged_bodyinstead.FileServernow forwards when a file is not found instead of failing with404 Not Found.Shieldis enabled by default. You may need to disable or change policies if your application depends on typically insecure browser features or if you wish to opt-in to different policies than the defaults.CookieJarget()s do not return cookies added during request handling. SeeCookieJar#pending.Hashimpls forMediaTypeandContentTypeno longer consider media type parameters.- When requested, the
FromFormimplementations ofVecandMaps are now properly lenient. - To agree with browsers, the
[and]characters are now accepted in URI paths. - The
[and]characters are no longer encoded byuri!. - The
Securecookie flag is set by default for all cookies when serving over TLS. - Removal cookies have
SameSiteset toLaxby default. MediaType::JavaScriptis nowtext/javascript.
Contrib Graduation
The rocket_contrib crate is deprecated and the functionality moved to other rocket crates. The
contrib deprecation upgrade guide provides a walkthrough on migrating. The relevant changes are:
- Several features previously in
rocket_contribwere merged intorocketitself:json,msgpack, anduuidare now features ofrocket.- Moved
rocket_contrib::jsontorocket::serde::json. - Moved
rocket_contrib::msgpacktorocket::serde::msgpack. - Moved
rocket_contrib::uuidtorocket::serde::uuid. - Moved
rocket_contrib::helmettorocket::shield.Shieldis enabled by default. - Moved
rocket_contrib::servetorocket::fs,StaticFilestorocket::fs::FileServer. - Removed the now unnecessary
UuidandJsonValuewrapper types. - Removed headers in
Shieldthat are no longer respected by browsers.
- The remaining features from
rocket_contribare now provided by separate crates:- Replaced
rocket_contrib::templateswithrocket_dyn_templates. - Replaced
rocket_contrib::databaseswithrocket_sync_db_poolsandrocket_db_pools. - These crates are versioned and released independently of
rocket. rocket_contrib::databases::DbErroris nowrocket_sync_db_pools::Error.- Removed
redis,mongodb, andmysqlintegrations which have upstreamasyncdrivers. - The
#[database]attribute generates anasync run()method instead ofDerefimplementations.
- Replaced
General
The following breaking changes apply broadly and are likely to cause compile-time errors.
Rocketis now generic over a phase marker:- APIs operate on
Rocket<Build>,Rocket<Ignite>,Rocket<Orbit>, orRocket<P: Phase>as needed. - The phase marker statically enforces state transitions in
Build,Ignite,Orbitorder. rocket::ignite()is nowrocket::build()and returns aRocket<Build>.Rocket::ignite()transitions to theIgnitephase. This is run automatically on launch as needed.- Ignition finalizes configuration, runs
ignitefairings, and verifies sentinels. Rocket::launch()transitions into theOrbitphase and starts the server.- Methods like
Request::rocket()that refer to a live Rocket instance return an&Rocket<Orbit>.
- APIs operate on
- Fairings have been reorganized and restructured for
async:- Replaced
attachfairings withignitefairings. Unlikeattachfairings, which ran immediately at the time of attachment,ignitefairings are run when transitioning into theIgnitephase. - Replaced
launchfairings withliftofffairings.liftofffairings are always run, even in local clients, after the server begins listening and the concrete port is known.
- Replaced
- Introduced a new configuration system based on Figment:
- The concept of "environments" is replaced with "profiles".
ROCKET_ENVis superseded byROCKET_PROFILE.ROCKET_LOGis superseded byROCKET_LOG_LEVEL.- Profile names can now be arbitrarily chosen. The
dev,stage, andprodprofiles carry no special meaning. - The
debugandreleaseprofiles are the default profiles for the debug and release compilation profiles. - A new specially recognized
defaultprofile specifies defaults for all profiles. - The
globalprofile has highest precedence, followed by the selected profile, followed bydefault. - Added support for limits specified in SI units: "1 MiB".
- Renamed
LoggingLeveltoLogLevel. - Inlined error variants into the
Errorstructure. - Changed the type of
workerstousizefromu16. - Changed accepted values for
keep_alive: it is disabled with0, notfalseoroff. - Disabled the
secretsfeature (for private cookies) by default. - Removed APIs related to "extras". Typed values can be extracted from the configured
Figment. - Removed
ConfigBuilder: all fields ofConfigare public with constructors for each field type.
- Many functions, traits, and trait bounds have been modified for
async:FromRequest,Fairing,catcher::Handler,route::Handler, andFromDatause#[async_trait].NamedFile::openis now anasyncfunction.- Added
Request::local_cache_async()for use in async request guards. - Unsized
Responsebodies must beAsyncReadinstead ofRead. - Automatically sized
Responsebodies must beAsyncSeekinstead ofSeek. - The
localmodule is split into two:rocket::local::asynchronousandrocket::local::blocking.
- Functionality and features requiring Rust nightly were removed:
- Removed the
Tryimplementation onOutcomewhich allowed using?withOutcomes. The recommended replacement is therocket::outcome::try_outcome!macro or the various combinator functions onOutcome. Result<T, E>implementsResponderonly when bothTandEimplementResponder. The newDebugwrapping responder replacesResult<T: Responder, E: Debug>.- APIs which used the
!type to now usestd::convert::Infallible.
- Removed the
IntoOutcomewas overhauled to supplant methods now removed inOutcome.IntoOutcome::into_outcome()is nowor_error().IntoOutcomeis implemented for allOutcometype aliases.Outcome::forward()requires specifying a status code.Outcome::from()andOutcome::from_or_forward()were removed.
Rocket::register()now takes a base path to scope catchers under as its first argument.ErrorKind::Collisionhas been renamed toErrorKind::Collisions.- TLS config values are only available when the
tlsfeature is enabled. MediaType::with_params()andContentType::with_params()are now builder methods.- Content-Type
contentresponder type names are now prefixed withRaw. - The
content::Plainresponder is now calledcontent::RawText. - The
content::Custom<T>responder was removed in favor of(ContentType, T). - Removed
CookieJar::get_private_pending()in favor ofCookieJar::get_pending(). - The
local_cache!macro accepts fewer types. Uselocal_cache_once!as appropriate. Rocket::launch()allowsRocketrecovery by returning the instance after shutdown.ErrorKind::Runtimewas removed;ErrorKind::Shutdownwas added.Outcome::Failurewas renamed toOutcome::Error.
Routing and URIs
- In
#[route(GET, path = "...")],pathis nowuri:#[route(GET, uri = "...")]. - Multi-segment paths (
/<p..>) now match zero or more segments. - Codegen improvements preclude identically named routes and modules in the same namespace.
- A route URI like (
/<a>/<p..>) now collides with (/<a>), requires arankto resolve. - All catcher related types and traits moved to
rocket::catcher. - All route related types and traits moved to
rocket::route. - URI formatting types and traits moved to
rocket::http::uri::fmt. Tno longer converts toOption<T>orResult<T, _>foruri!query parameters.- For optional query parameters,
uri!requires using a wrapped value or_. &RawStrno longer implementsFromParam: use&strinstead.- Percent-decoding is performed before calling
FromParamimplementations. RawStr::url_decode()andRawStr::url_decode_lossy()allocate as necessary, returnCow.RawStr::from_str()was replaced withRawStr::new().Origin::segments()was replaced withOrigin.path().segments().Origin::path()andOrigin::query()return&RawStrinstead of&str.- The type of
Route::nameis nowOption<Cow<'static, str>>. Route::set_uriwas replaced withRoute::map_base().- The
Route::urifield is now of typeRouteUri. Route::basewas removed in favor ofRoute.uri().base().- Route
Forwardoutcomes are now associated with aStatus. - The status codes used when built-in guards forward were changed:
- Route parameter
FromParamerrors now forward as 422. - Query parameter errors now forward as 422.
- Incorrect form content-type errors forwards as 413.
&Host,&Accept,&ContentType,IpAddr, andSocketAddrall forward with a 500.
- Route parameter
Data and Forms
Datanow has a lifetime generic:Data<'r>.Data::open()indelibly requires a data limit.- Removed
FromDataSimple. UseFromDataandlocal_cache!orlocal_cache_once!. - All
DataStreamAPIs require limits and returnCapped<T>types. - Form types and traits were moved from
rocket::requesttorocket::form. - Removed
FromQuery. Dynamic query parameters (#[get("/?<param>")]) useFromForminstead. - Replaced
FromFormValuewithFromFormField. AllT: FromFormFieldimplementFromForm. - Form field values are percent-decoded before calling
FromFormFieldimplementations. - Renamed the
#[form(field = ...)]attribute to#[field(name = ...)]. - Custom form errors must now specify an associated
Status.
Request Guards
- Renamed
CookiestoCookieJar. Its methods take&self. - Renamed
Flash.nametoFlash.kind,Flash.msgtoFlash.message. - Replaced
Request::get_param()withRequest::param(). - Replaced
Request::get_segments()toRequest::segments(). - Replaced
Request::get_query_value()withRequest::query_value(). - Replaced
Segments::into_path_buf()withSegments::to_path_buf(). - Replaced
SegmentsandQuerySegmentswithSegments<Path>andSegments<Query>. Flashconstructors now takeInto<String>instead ofAsRef<str>.- The
State<'_, T>request guard is now&State<T>. - Removed a lifetime from
FromRequest:FromRequest<'r>. - Removed a lifetime from
FlashMessage:FlashMessage<'_>. - Removed all
Statereexports exceptrocket::State.
Responders
- Moved
NamedFiletorocket::fs::NamedFile - Replaced
Contentwithcontent::Custom. Response::bodyandResponse::body_mutare now infallible methods.- Renamed
ResponseBuildertoBuilder. - Removed direct
Responsebody reading methods. Use methods onr.body_mut()instead. - Removed inaccurate "chunked body" types and variants.
- Removed
ResponderimplforResponse. Prefer custom responders with#[derive(Responder)]. - Removed the unused reason phrase from
Status. - The types of responders in
response::statuswere unified to all be of the formStatus<R>(R).
General Improvements
In addition to new features and changes, Rocket saw the following improvements:
General
- Added support for raw identifiers in the
FromFormderive,#[route]macros, anduri!. - Added support for uncased derived form fields:
#[field(name = uncased(...))]. - Added support for default form field values:
#[field(default = expr())]. - Added support for multiple
#[field]attributes on struct fields. - Added support for base16-encoded (a.k.a. hex-encoded) secret keys.
- Added
Config::identfor configuring or removing the globalServerheader. - Added
Rocket::figment()andRocket::catchers(). - Added
LocalRequest::json()andLocalResponse::json(). - Added
LocalRequest::msgpack()andLocalResponse::msgpack(). - Added support for
use m::route; routes![route]instead of needingroutes![m::route]. - Added support for hierarchical data limits: a limit of
a/b/cfalls back toa/bthena. - Added
LocalRequest::inner_mut().LocalRequestimplementsDerefMuttoRequest. - Added support for ECDSA and EdDSA TLS keys.
- Added associated constants in
Configfor all config parameter names. - Added
ErrorKind::Configto represent errors in configuration at runtime. - Added
rocket::fairing::Resulttype alias, returned byFairing::on_ignite(). - All guard failures are logged at runtime.
Rocket::mount()now accepts a base value of any type that implementsTryInto<Origin<'_>>.- The default error catcher's HTML has been compacted.
- The default error catcher returns JSON if requested by the client.
- Panics in routes or catchers are caught and forwarded to
500error catcher. - A detailed warning is emitted if a route or catcher panics.
- Emoji characters are no longer output on Windows.
- Fixed
Errorto not panic if a panic is already in progress. - Introduced
ReferenceandAsteriskURI types. - Added support to
UriDisplayQueryfor C-like enums. - The
UriDisplayQueryderive now recognizes the#[field]attribute for field renaming. Clientmethod builders acceptTryInto<Origin>allowing auri!()to be used directly.Rocketis now#[must_use].- Support for HTTP/2 can be disabled by disabling the default
http2crate feature. - Added
rocket::execute()for executing Rocket'slaunch()future. - Added the
context!macro torocket_dyn_templatesfor ad-hoc template contexts. - The
timecrate is re-exported from the crate root. - The
FromForm,Responder, andUriDisplayderives now fully support generics. - Added helper functions to
serdesubmodules. - The
ShieldHSTS preload header now includesincludeSubdomains. - Logging ignores
write!errors ifstdoutdisappears, preventing panics. - Added
Client::terminate()to run graceful shutdown in testing. - Shutdown now terminates the
asyncruntime, never the process. - Added a
local_cache_once!macro for request-local storage. - Final launch messages are now always logged, irrespective of profile.
- Only functions that return
Rocket<Build>are now#[must_use], not allRocket<P>. - Fixed mismatched form field names in errors under certain conditions in
FromFormderive. - The
FromFormderive now collects all errors that occur. - Data pools are now gracefully shutdown in
rocket_sync_db_pools. - Added
Metadata::render()inrocket_dyn_templatesfor direct template rendering. - Rocket salvages more information from malformed requests for error catchers.
- The
cookiesecurefeature is now properly conditionally enabled. - Data before encapsulation boundaries in TLS keys is allowed and ignored.
- Support for TLS keys in SEC1 format was added.
- Rocket now warns when a known secret key is configured.
- A panic that could occur on shutdown in
rocket_sync_db_poolswas fixed. - Added a
max_blockingconfiguration parameter to control number of blocking threads. - Added an
ip_header"real IP" header configuration parameter. - A
pool()method is emitted byrocket_sync_db_poolsfor code-generated pools. - Data guards are now eligible sentinels.
- Raw binary form field data can be retrieved using the
&[u8]form guard. - Added
TempFile::open()to streamTempFiledata. - mTLS certificates can be set on local requests with
LocalRequest::identity(). - Added
Error::pretty_print()for pretty-printing errors like Rocket. - Warnings are logged when data limits are reached.
- A warning is emitted when
Stringis used as a route parameter. - Configuration provenance information is logged under the
debuglog level. - Logging of
Outcomes now includes the relevant status code. Span::mixed_site()is used in codegen to reduce errantclippywarnings.
HTTP
- Added support for HTTP/2, enabled by default via the
http2crate feature. - Added a
constconstructor forMediaType. - Introduced
RawStrBuf, an ownedRawStr. - Added many new "pattern" methods to
RawStr. - Added
RawStr::percent_encode()andRawStr::strip(). - Added support for unencoded query characters in URIs that are frequently sent by browsers.
- Introduced
Hostand&Hostrequest guards. - Added
RawStr::percent_encode_bytes(). NODELAYis now enabled on all connections by default.- The TLS implementation handles handshakes off the main task, improving DoS resistance.
Known Media Types
- Added AVIF:
image/avif. - Added
EventStream:text/event-stream. - Added
Markdown:text/markdown. - Added
MP3:audio/mpeg. - Added
CBZ:application/vnd.comicbook+zip, extension.cbz. - Added
CBR:application/vnd.comicbook-rar, extension.cbr. - Added
RAR:application/vnd.rar, extension.rar. - Added
EPUB:application/epub+zip, extension.epub. - Added
OPF:application/oebps-package+xml, extension.opf. - Added
XHTML:application/xhtml+xml, extension.xhtml. - Added
Textas an alias for thePlainmedia type. - Added
Bytesas an alias for theBinarymedia type. - Added
.mjsas known JavaScript extension. - Added '.exe', '.iso', '.dmg' as known extensions.
Request
- Added support for all UTF-8 characters in route paths.
- Added support for percent-encoded
:in socket or IP address values inFromFormValue. - Added
Request::rocket()to access the activeRocketinstance. Request::uri()now returns an&Origin<'r>instead of&Origin<'_>.Request::accept(),Request::content_type()reflect changes toAccept,Content-Type.Json<T>,MsgPack<T>acceptT: Deserialize, not onlyT: DeserializeOwned.- Diesel SQLite connections in
rocket_sync_db_poolsuse better defaults. - The default number of workers for synchronous database pools is now
workers * 4. - Added
Request::host()to retrieve the client-requested host.
Response
- Added
Template::try_custom()for fallible template engine customization. - Manually registered templates can now be rendered with
Template::render(). - Added support for the
X-DNS-Prefetch-Controlheader toShield. - Added support for manually-set
expiresvalues for private cookies. - Added support for type generics and custom generic bounds to
#[derive(Responder)]. - The
Serverheader is only set if one isn't already set. - Accurate
Content-Lengthheaders are sent even for partially readBodys. Redirectnow accepts aTryFrom<Reference>, allowing fragment parts.
Trait Implementations
- Implemented
CloneforState. - Implemented
CopyandCloneforfairing::Info. - Implemented
DebugforRocketandClient. - Implemented
DefaultforStatus(returnsStatus::Ok). - Implemented
PartialEq,Eq,Hash,PartialOrd, andOrdforStatus. - Implemented
Eq,Hash, andPartialEq<&str>forOrigin. - Implemented
PartialEq<Cow<'_, RawStr>>>forRawStr. - Implemented
std::error::ErrorforError. - Implemented
DerefandDerefMutforLocalRequest(toRequest). - Implemented
DerefMutforForm,LenientForm. - Implemented
From<T>forJson<T>,MsgPack<T>. - Implemented
TryFrom<String>andTryFrom<&str>forOrigin. - Implemented
TryFrom<Uri>for each of the specific URI variants. - Implemented
FromRequestfor&Config. - Implemented
FromRequestforIpAddr. - Implemented
FromParamforPathBuf - Implemented
FromParam,FromData, andFromFormfor&str. - Implemented
FromFormforJson<T>,MsgPack<T>. - Implemented
FromFormFieldforCowandCapped<Cow>> - Implemented
Responderfortokio::fs::File. - Implemented
Responderfor(ContentType, R) where R: Responder. - Implemented
Responderfor(Status, R) where R: Responderwhich overridesR's status. - Implemented
Responderforstd::io::Error(behaves asDebug<std::io::Error>). - Implemented
ResponderforEither<T, E>, equivalently toResult<T, E>. - Implemented
SerializeforFlash. - Implemented
Serialize,Deserialize,UriDisplayandFromUriParamforuuid::Uuid - Implemented
Serialize,DeserializeforRawStr. - Implemented
Serialize,Deserializefor all URI types. - Implemented
ResponderforArc<T>,Box<T>whereT: Responder. - Implemented
SerializeandDeserializeforMethod. - Implemented
EqforMediaTypeandContentType. - Implemented
ResponderforBox<T: Responder + Sized>. - Implemented
FromFormforArc<T>. - Implemented
FairingforArc<dyn Fairing>. - Implemented
SerializeandDeserializeforStatus.
Dependency Changes
serdewas introduced (1.0).futureswas introduced (0.3).binasciiwas introduced (0.1).ref-castwas introduced (1.0).atomicwas introduced (0.5).parking_lotwas introduced (0.11).ubtyewas introduced (0.10).figmentwas introduced (0.10).randwas introduced (0.8).eitherwas introduced (1.0).pin-project-litewas introduced (0.2).indexmapwas introduced (2.0).tempfilewas introduced (3.0).async-traitwas introduced (0.1).async-streamwas introduced (0.3).multerwas introduced (2.0).tokiowas introduced (1.6.1).tokio-utilwas introduced (0.6).tokio-streamwas introduced (0.1.6).byteswas introduced (1.0).normpathwas introduced (1).statewas updated to0.6.rmp-serdewas updated to0.15.uuidwas updated to0.8.terawas updated to1.10.postgreswas updated to0.19.rusqlitewas updated to0.25.r2d2_sqlitewas updated to0.18.timewas updated to0.3.handlebarswas updated to4.0.memcachewas updated to0.16.rustlswas updated to0.21.tokio-rustlswas updated to0.24.synwas updated to2.dieselwas updated to2.0.sqlxwas updated to0.7.notifywas updated to6.criterionwas updated to0.4.cookiewas updated to0.18.yansiwas updated to1.0.attywas removed.
Infrastructure
The following changes were made to the project's infrastructure:
- Rocket now uses the 2021 edition of Rust.
- Added a v0.4 to v0.5 migration guide and FAQ to Rocket's website.
- Added visible
usestatements to examples in the guide. - Split examples into a separate workspace for easier testing.
- Updated documentation for all changes.
- Fixed many typos, errors, and broken links throughout documentation and examples.
- Improved the general robustness of macros, and the quality and frequency of error messages.
- Benchmarks now use
criterionand datasets extracted from real-world projects. - Fixed the SPDX license expressions in
Cargo.tomlfiles. - Added support to
test.shfor a+flag (e.g.+stable) to pass tocargo. - Added support to
test.shfor extra flags to be passed on tocargo. - UI tests are now allowed to fail by the CI to avoid false negatives.
- The GitHub CI workflow was updated to use maintained actions.
- The CI now frees disk space before proceeding to avoid out-of-disk errors.
- All workspaces now use
resolver = 2.
Version 0.4.10 (May 21, 2021)
Core
- [
3276b8] RemovedunsafeinOrigin::parse_owned(), fixing a soundness issue.
Version 0.4.9 (May 19, 2021)
Core
Version 0.4.8 (May 18, 2021)
Core
- [
#1548,93e88b0] Fixed an issue that prevented compilation under Windows Subsystem for Linux v1. - Updated
OutcomeTryimplementation to v2 in latest nightly. - Minimum required
rustcis1.54.0-nightly (2021-05-18).
Internal
- Updated
base64dependency to0.13.
Version 0.4.7 (Feb 09, 2021)
Core
Version 0.4.6 (Nov 09, 2020)
Core
- [
86bd7c] Added default and configurable read/write timeouts:read_timeoutandwrite_timeout. - [
c24a96] Added thessefeature, which enables flushing by returningio::ErrorKind::WouldBlock.
Docs
- Fixed broken doc links in
contrib. - Fixed database library versions in
contribdocs.
Internal
- Updated source code for Rust 2018.
- UI tests now use
trybuildinstead ofcompiletest-rs.
Version 0.4.5 (May 30, 2020)
Core
- [#1312,
89150f] Fixed a low-severity, minimal impact soundness issue inLocalRequest::clone(). - [#1263,
376f74] Fixed a cookie serialization issue that led to incorrect cookie deserialization in certain cases. - Removed dependency on
ringfor private cookies and thus Rocket, by default. - Added
Origin::map_path()for manipulatingOriginpaths. - Added
handler::Outcome::from_or_forward(). - Added
Options::NormalizeDirsoption toStaticFiles. - Improved accessibility of default error HTML.
Docs
- Fixed various typos.
Version 0.4.4 (Mar 09, 2020)
Core
- Removed use of unsupported
cfg(debug_assertions)inCargo.toml, allowing for builds on latest nightlies.
Docs
- Fixed various broken links.
Version 0.4.3 (Feb 29, 2020)
Core
- Added a new
Debug500ResponderthatDebug-prints its contents on response. - Specialization on
Resultwas deprecated.Debugcan be used in place of non-Respondererrors. - Fixed an issue that resulted in cookies not being set on error responses.
- Various
Debugimplementations on Rocket types now respect formatting options. - Added
Responders for various HTTP status codes:NoContent,Unauthorized,Forbidden, andConflict. FromParamis implemented forNonZerocore types.
Codegen
- Docs for Rocket-generated macros are now hidden.
- Generated code now works even when prelude imports like
Some,Ok, andErrare shadowed. - Error messages referring to responder types in routes now point to the type correctly.
Docs
- All code examples in the guide are now tested and guaranteed to compile.
- All macros are documented in the
corecrate;rocket_codegenmakes no appearances.
Infrastructure
- CI was moved from Travis to Azure Pipelines; Windows support is tested.
- Rocket's chat moved to Matrix and Freenode.
Version 0.4.2 (Jun 28, 2019)
Core
- Replaced use of
FnBoxwithBox<dyn FnOnce>. - Removed the stable feature gates
try_fromandtranspose_result. - Derive macros are reexported alongside their respective traits.
- Minimum required
rustcis1.35.0-nightly (2019-04-05).
Codegen
JsonValuenow implementsFromIterator.non_snake_caseerrors are silenced in generated code.- Minimum required
rustcis1.33.0-nightly (2019-01-03).
Contrib
- Allow setting custom ranks on
StaticFilesviaStaticFiles::rank(). MsgPackcorrectly sets a MessagePack Content-Type on responses.
Docs
- Fixed typos across rustdocs and guide.
- Documented library versions in contrib database documentation.
Infrastructure
- Updated internal dependencies to their latest versions.
Version 0.4.1 (May 11, 2019)
Core
- Rocket's default
ServerHTTP header no longer overrides a user-set header. - Fixed encoding and decoding of certain URI characters.
Codegen
- Compiler diagnostic information is more reliably produced.
Contrib
- Database pool types now implement
DerefMut. - Added support for memcache connection pools.
- Stopped depending on default features from core.
Docs
- Fixed many typos across the rustdocs and guide.
- Added guide documentation on mounting more than one route at once.
Infrastructure
- Testing no longer requires "bootstrapping".
- Removed deprecated
isattydependency in favor ofatty.
Version 0.4.0 (Dec 06, 2018)
New Features
This release includes the following new features:
- Introduced Typed URIs.
- Introduced ORM agnostic database support.
- Introduced Request-Local State.
- Introduced mountable static-file serving via
StaticFiles. - Introduced automatic live template reloading.
- Introduced custom stateful handlers via
Handler. - Introduced transforming data guards via
FromData::transform(). - Introduced revamped query string handling.
- Introduced the
SpaceHelmetsecurity and privacy headers fairing. - Private cookies are gated behind a
private-cookiesdefault feature. - Added derive for
FromFormValue. - Added derive for
Responder. - Added
Template::custom()for customizing templating engines including registering filters and helpers. - Cookies are automatically tracked and propagated by
Client. - Private cookies can be added to local requests with
LocalRequest::private_cookie(). - Release builds default to the
productionenvironment. - Keep-alive can be configured via the
keep_aliveconfiguration parameter. - Allow CLI colors and emoji to be disabled with
ROCKET_CLI_COLORS=off. - Route
formataccepts shorthands such asjsonandhtml. - Implemented
ResponderforStatus. - Added
Response::cookies()for retrieving response cookies. - All logging is disabled when
logis set tooff. - Added
Metadataguard for retrieving templating information. - The
Uritype parses URIs according to RFC 7230 into one ofOrigin,Absolute, orAuthority. - Added
Outcome::and_then(),Outcome::failure_then(), andOutcome::forward_then(). - Implemented
Responderfor&[u8]. - Any
T: Into<Vec<Route>>can bemount()ed. - Default rankings range from -6 to -1, differentiating on static query strings.
- Added
Request::get_query_value()for retrieving a query value by key. - Applications can launch without a working directory.
- Added
State::from()for constructingStatevalues.
Codegen Rewrite
The rocket_codegen crate has been entirely rewritten using to-be-stable
procedural macro APIs. We expect nightly breakages to drop dramatically, likely
to zero, as a result. The new prelude import for Rocket applications is:
- #![feature(plugin)]
- #![plugin(rocket_codegen)]
+ #![feature(proc_macro_hygiene, decl_macro)]
- extern crate rocket;
+ #[macro_use] extern crate rocket;
The rocket_codegen crate should not be a direct dependency. Remove it
from your Cargo.toml:
[dependencies]
- rocket = "0.3"
+ rocket = "0.4"
- rocket_codegen = "0.3"
Breaking Changes
This release includes many breaking changes. These changes are listed below along with a short note about how to handle the breaking change in existing applications when applicable.
-
Route and catcher attributes respect function privacy.
To mount a route or register a catcher outside of the module it is declared, ensure that the handler function is marked
puborcrate. -
Query handling syntax has been completely revamped.
A query parameter of
<param>is now<param..>. Consider whether your application benefits from the revamped query string handling. -
The
#[error]attribute anderrors!macro were removed.Use
#[catch]andcatchers!instead. -
Rocket::catch()was renamed toRocket::register().Change calls of the form
.catch(errors![..])to.register(catchers![..]). -
The
#[catch]attribute only accepts functions with 0 or 1 argument.Ensure the argument to the catcher, if any, is of type
&Request. -
json!returns aJsonValue, no longer needs wrapping.Change instances of
Json(json!(..))tojson!and change the corresponding type toJsonValue. -
All environments default to port 8000.
Manually configure a port of
80for thestageandproductionenvironments for the previous behavior. -
Release builds default to the production environment.
Manually set the environment to
debugwithROCKET_ENV=debugfor the previous behavior. -
FormandLenientFormlost a lifetime parameter,get()method.Change a type of
Form<'a, T<'a>>toForm<T>orForm<T<'a>>.Form<T>andLenientForm<T>now implementDeref<Target = T>, allowing for calls to.get()to be removed. -
ringwas updated to 0.13.Ensure all transitive dependencies to
ringrefer to version0.13. -
Uriwas largely replaced byOrigin.In general, replace the type
UriwithOrigin. Thebaseandurifields ofRouteare now of typeOrigin. The&Uriguard is now&Origin.Request::uri()now returns anOrigin. -
All items in
rocket_contribare namespaced behind modules.Jsonis nowjson::JsonMsgPackis nowmsgpack::MsgPackMsgPackErroris nowmsgpack::ErrorTemplateis nowtemplates::TemplateUUIDis nowuuid::UuidValueis replaced byjson::JsonValue
-
TLS certificates require the
subjectAltNameextension.Ensure that your TLS certificates contain the
subjectAltNameextension with a value set to your domain. -
Route paths, mount points, and
LocalRequestURIs are strictly checked.Ensure your mount points are absolute paths with no parameters, ensure your route paths are absolute paths with proper parameter syntax, and ensure that paths passed to
LocalRequestare valid. -
Template::show()takes an&Rocket, doesn't accept aroot.Use
client.rocket()to get a reference to an instance ofRocketwhen testing. UseTemplate::render()in routes. -
Request::remote()returns the actual remote IP, doesn't rewrite.Use
Request::real_ip()orRequest::client_ip()to retrieve the IP address from the "X-Real-IP" header if it is present. -
Bindvariant was added toLaunchErrorKind.Ensure matches on
LaunchErrorKindinclude or ignore theBindvariant. -
Cookies are automatically tracked and propagated by
Client.For the previous behavior, construct a
ClientwithClient::untracked(). -
UUIDwas renamed toUuid.Use
Uuidinstead ofUUID. -
LocalRequest::cloned_dispatch()was removed.Chain calls to
.clone().dispatch()for the previous behavior. -
Redirectconstructors take a generic type ofT: TryInto<Uri<'static>>.A call to a
Redirectconstructor with a non-'static&strof the formRedirect::to(string)should becomeRedirect::to(string.to_string()), heap-allocating the string before being passed to the constructor. -
The
FromDataimpl forFormandLenientFormnow return an error of typeFormDataError.On non-I/O errors, the form string is stored in the variant as an
&'f str. -
Missingvariant was added toConfigError.Ensure matches on
ConfigErrorinclude or ignore theMissingvariant. -
The
FromDataimpl forJsonnow returns an error of typeJsonError.The previous
SerdeErroris now the.1member of theJsonErrorenum. Match and destruct the variant for the previous behavior. -
FromDatais now emulated byFromDataSimple.Change implementations, not uses, of
FromDatatoFromDataSimple. Consider whether your implementation could benefit from transformations. -
FormItemsiterates over values of typeFormItem.Map using
.map(|item| item.key_value())for the previous behavior. -
LaunchErrorKind::Collisioncontains a vector of the colliding routes.Destruct using
LaunchErrorKind::Collision(..)to ignore the vector. -
Request::get_param()andRequest::get_segments()are indexed by segment, not dynamic parameter.Modify the
nargument in calls to these functions appropriately. -
Method-based route attributes no longer accept a keyed
pathparameter.Change an attribute of the form
#[get(path = "..")]to#[get("..")]. -
JsonandMsgPackdata guards no longer reject requests with an unexpected Content-TypeTo approximate the previous behavior, add a
format = "json"route parameter when usingJsonorformat = "msgpack"when usingMsgPack. -
Implemented
ResponderforStatus. RemovedFailure,status::NoContent, andstatus::Resetresponders.Replace uses of
Failure(status)withstatusdirectly. Replacestatus::NoContentwithStatus::NoContent. Replacestatus::ResetwithStatus::ResetContent. -
Config::root()returns anOption<&Path>instead of an&Path.For the previous behavior, use
config.root().unwrap(). -
Status::new()is no longerconst.Construct a
Statusdirectly. -
Configconstructors return aConfiginstead of aResult<Config>. -
ConfigError::BadCWD,Config.config_pathwere removed. -
Jsonno longer has a default value for its type parameter. -
Using
dataon a non-payload method route is a warning instead of error. -
The
raw_form_stringmethod ofFormandLenientFormwas removed. -
Various impossible
Errorassociated types are now set to!. -
All
AdHocconstructors require a name as the first parameter. -
The top-level
Errortype was removed.
General Improvements
In addition to new features, Rocket saw the following improvements:
- Log messages now refer to routes by name.
- Collision errors on launch name the colliding routes.
- Launch fairing failures refer to the failing fairing by name.
- The default
403catcher now references authorization, not authentication. - Private cookies are set to
HttpOnlyand are given an expiration date of 1 week by default. - A Tera templates example was added.
- All macros, derives, and attributes are individually documented in
rocket_codegen. - Invalid client requests receive a response of
400instead of500. - Response bodies are reliably stripped on
HEADrequests. - Added a default catcher for
504: Gateway Timeout. - Configuration information is logged in all environments.
- Use of
unsafewas reduced from 9 to 2 in core library. FormItemsnow parses empty keys and values as well as keys without values.- Added
Config::active()as a shorthand forConfig::new(Environment::active()?). - Address/port binding errors at launch are detected and explicitly emitted.
Flashcookies are cleared only after they are inspected.Syncbound onAdHoc::on_attach(),AdHoc::on_launch()was removed.AdHoc::on_attach(),AdHoc::on_launch()accept anFnOnce.- Added
Config::root_relative()for retrieving paths relative to the configuration file. - Added
Config::tls_enabled()for determining whether TLS is actively enabled. - ASCII color codes are not emitted on versions of Windows that do not support them.
- Added FLAC (
audio/flac), Icon (image/x-icon), WEBA (audio/webm), TIFF (image/tiff), AAC (audio/aac), Calendar (text/calendar), MPEG (video/mpeg), TAR (application/x-tar), GZIP (application/gzip), MOV (video/quicktime), MP4 (video/mp4), ZIP (application/zip) as known media types. - Added
.weba(WEBA),.ogv(OGG),.mp4(MP4),.mpeg4(MP4),.aac(AAC),.ics(Calendar),.bin(Binary),.mpg(MPEG),.mpeg(MPEG),.tar(TAR),.gz(GZIP),.tif(TIFF),.tiff(TIFF),.mov(MOV) as known extensions. - Interaction between route attributes and declarative macros has been improved.
- Generated code now logs through logging infrastructures as opposed to using
println!. - Routing has been optimized by caching routing metadata.
FormandLenientFormcan be publicly constructed.- Console coloring uses default terminal colors instead of white.
- Console coloring is consistent across all messages.
i128andu128now implementFromParam,FromFormValue.- The
base64dependency was updated to0.10. - The
logdependency was updated to0.4. - The
handlebarsdependency was updated to1.0. - The
teradependency was updated to0.11. - The
uuiddependency was updated to0.7. - The
rustlsdependency was updated to0.14. - The
cookiedependency was updated to0.11.
Infrastructure
- All documentation is versioned.
- Previous, current, and development versions of all documentation are hosted.
- The repository was reorganized with top-level directories of
coreandcontrib. - The
httpmodule was split into its ownrocket_httpcrate. This is an internal change only. - All uses of
unsafeare documented with informal proofs of correctness.
Version 0.3.16 (Aug 24, 2018)
Codegen
- Codegen was updated for
2018-08-23nightly. - Minimum required
rustcis1.30.0-nightly 2018-08-23.
Core
- Force close only the read end of connections. This allows responses to be sent even when the client transmits more data than expected.
Docs
- Add details on retrieving configuration extras to guide.
Version 0.3.15 (Jul 16, 2018)
Codegen
- The
#[catch]decorator andcatchers!macro were introduced, replacing#[error]anderrors!. - The
#[error]decorator anderrors!macro were deprecated. - Codegen was updated for
2018-07-15nightly. - Minimum required
rustcis1.29.0-nightly 2018-07-15.
Version 0.3.14 (Jun 22, 2018)
Codegen
- Codegen was updated for
2018-06-22nightly. - Minimum required
rustcis1.28.0-nightly 2018-06-22.
Version 0.3.13 (Jun 16, 2018)
Codegen
- Codegen was updated for
2018-06-12nightly. - Minimum required
rustcis1.28.0-nightly 2018-06-12.
Version 0.3.12 (May 31, 2018)
Codegen
- Codegen was updated for
2018-05-30nightly. - Minimum required
rustcis1.28.0-nightly 2018-05-30.
Version 0.3.11 (May 19, 2018)
Core
- Core was updated for
2018-05-18nightly.
Infrastructure
- Fixed injection of dependencies for codegen compile-fail tests.
Version 0.3.10 (May 05, 2018)
Core
- Fixed parsing of nested TOML structures in config environment variables.
Codegen
- Codegen was updated for
2018-05-03nightly. - Minimum required
rustcis1.27.0-nightly 2018-05-04.
Contrib
- Contrib was updated for
2018-05-03nightly.
Docs
- Fixed database pool type in state guide.
Version 0.3.9 (Apr 26, 2018)
Core
- Core was updated for
2018-04-26nightly. - Minimum required
rustcis1.27.0-nightly 2018-04-26. - Managed state retrieval cost was reduced to an unsynchronized
HashMaplookup.
Codegen
- Codegen was updated for
2018-04-26nightly. - Minimum required
rustcis1.27.0-nightly 2018-04-26.
Contrib
- A 512-byte buffer is preallocated when deserializing JSON, improving performance.
Docs
- Fixed various typos in rustdocs and guide.
Version 0.3.8 (Apr 07, 2018)
Codegen
- Codegen was updated for
2018-04-06nightly. - Minimum required
rustcis1.27.0-nightly 2018-04-06.
Version 0.3.7 (Apr 03, 2018)
Core
- Fixed a bug where incoming request URIs would match routes with the same path prefix and suffix and ignore the rest.
- Added known media types for WASM, WEBM, OGG, and WAV.
- Fixed fragment URI parsing.
Codegen
- Codegen was updated for
2018-04-03nightly. - Minimum required
rustcis1.27.0-nightly 2018-04-03.
Contrib
- JSON data is read eagerly, improving deserialization performance.
Docs
- Database example and docs were updated for Diesel 1.1.
- Removed outdated README performance section.
- Fixed various typos in rustdocs and guide.
Infrastructure
- Removed gates for stabilized features:
iterator_for_each,i128_type,conservative_impl_trait,never_type. - Travis now tests in both debug and release mode.
Version 0.3.6 (Jan 12, 2018)
Core
Rocket.state()method was added to retrieve managed state fromRocketinstances.- Nested calls to
Rocket.attach()are now handled correctly. - JSON API (
application/vnd.api+json) is now a known media type. - Uncached markers for
ContentTypeandAcceptheaders are properly preserved onRequest.clone(). - Minimum required
rustcis1.25.0-nightly 2018-01-12.
Codegen
- Codegen was updated for
2017-12-22nightly. - Minimum required
rustcis1.24.0-nightly 2017-12-22.
Docs
- Fixed typo in state guide:
simplesimply. - Database example and docs were updated for Diesel 1.0.
Infrastructure
- Shell scripts now use
git grepinstead ofegrepfor faster searching.
Version 0.3.5 (Dec 18, 2017)
Codegen
- Codegen was updated for
2017-12-17nightly. - Minimum required
rustcis1.24.0-nightly 2017-12-17.
Version 0.3.4 (Dec 14, 2017)
Core
NamedFile'sResponderimplementation now uses a sized body when the file's length is known.#[repr(C)]is used onstrwrappers to guarantee correct structure layout across platforms.- A
status::BadRequestResponderwas added.
Codegen
- Codegen was updated for
2017-12-13nightly. - Minimum required
rustcis1.24.0-nightly 2017-12-13.
Docs
- The rustdoc
html_root_urlnow points to the correct address. - Fixed typo in fairings guide:
eventevents. - Fixed typo in
Outcomedocs:usersUsers.
Version 0.3.3 (Sep 25, 2017)
Core
Config'sDebugimplementation now respects formatting options.Cow<str>now implementsFromParam.Vec<u8>now implementsResponder.- Added a
Binarymedia type forapplication/octet-stream. - Empty fairing collections are no longer logged.
- Emojis are no longer emitted to non-terminals.
- Minimum required
rustcis1.22.0-nightly 2017-09-13.
Codegen
- Improved "missing argument in handler" compile-time error message.
- Codegen was updated for
2017-09-25nightly. - Minimum required
rustcis1.22.0-nightly 2017-09-25.
Docs
- Fixed typos in site overview:
bybe,ReponderResponder. - Markdown indenting was adjusted for CommonMark.
Infrastructure
- Shell scripts handle paths with spaces.
Version 0.3.2 (Aug 15, 2017)
Core
- Added conversion methods from and to
Box<UncasedStr>.
Codegen
- Lints were removed due to compiler instability. Lints will likely return as
a separate
rocket_lintscrate.
Version 0.3.1 (Aug 11, 2017)
Core
- Added support for ASCII colors on modern Windows consoles.
- Form field renames can now include any valid characters, not just idents.
Codegen
- Ignored named route parameters are now allowed (
_ident). - Fixed issue where certain paths would cause a lint
assert!to fail (#367). - Lints were updated for
2017-08-10nightly. - Minimum required
rustcis1.21.0-nightly (2017-08-10).
Contrib
- Tera errors that were previously skipped internally are now emitted.
Documentation
- Typos were fixed across the board.
Version 0.3.0 (Jul 14, 2017)
New Features
This release includes the following new features:
- Fairings, Rocket's structure middleware, were introduced.
- Native TLS support was introduced.
- Private cookies were introduced.
- A
MsgPacktype has been added tocontribfor simple consumption and returning of MessagePack data. - Launch failures (
LaunchError) fromRocket::launch()are now returned for inspection without panicking. - Routes without query parameters now match requests with or without query parameters.
- Default rankings range from -4 to -1, preferring static paths and routes with query string matches.
- A native
Acceptheader structure was added. - The
Acceptrequest header can be retrieved viaRequest::accept(). - Incoming form fields can be renamed via a new
#[form(field = "name")]structure field attribute. - All active routes can be retrieved via
Rocket::routes(). Response::body_string()was added to retrieve the response body as aString.Response::body_bytes()was added to retrieve the response body as aVec<u8>.Response::content_type()was added to easily retrieve the Content-Type header of a response.- Size limits on incoming data are now configurable.
Request::limits()was added to retrieve incoming data limits.- Responders may dynamically adjust their response based on the incoming request.
Request::guard()was added for simple retrieval of request guards.Request::route()was added to retrieve the active route, if any.&Routeis now a request guard.- The base mount path of a
Routecan be retrieved viaRoute::baseorRoute::base(). Cookiessupports private (authenticated encryption) cookies, encrypted with thesecret_keyconfig key.Config::{development, staging, production}constructors were added forConfig.Config::get_datetime()was added to retrieve an extra as aDatetime.- Forms can be now parsed leniently via the new
LenientFormdata guard. - The
?operator can now be used withOutcome. - Quoted string, array, and table based configuration parameters can be set via environment variables.
- Log coloring is disabled when
stdoutis not a TTY. FromFormis implemented forOption<T: FromForm>,Result<T: FromForm, T::Error>.- The
NotFoundresponder was added for simple 404 response construction.
Breaking Changes
This release includes many breaking changes. These changes are listed below along with a short note about how to handle the breaking change in existing applications.
-
session_keywas renamed tosecret_key, requires a 256-bit base64 keyIt's unlikely that
session_keywas previously used. If it was, renamesession_keytosecret_key. Generate a random 256-bit base64 key using a tool like openssl:openssl rand -base64 32. -
The
&Cookiesrequest guard has been removed in favor ofCookiesChange
&Cookiesin a request guard position toCookies. -
Rocket::launch()now returns aLaunchError, doesn't panic.For the old behavior, suffix a call to
.launch()with a semicolon:.launch();. -
Routes without query parameters match requests with or without query parameters.
There is no workaround, but this change may allow manual ranks from routes to be removed.
-
The
formatroute attribute on non-payload requests matches against the Accept header.Excepting a custom request guard, there is no workaround. Previously,
formatalways matched against the Content-Type header, regardless of whether the request method indicated a payload or not. -
A type of
&strcan no longer be used in form structures or parameters.Use the new
&RawStrtype instead. -
ContentTypeis no longer a request guard.Use
&ContentTypeinstead. -
Request::content_type()returns&ContentTypeinstead ofContentType.Use
.clone()on&ContentTypeif a type ofContentTypeis required. -
Response::header_values()was removed.Response::headers()now returns an&HeaderMap.A call to
Response::headers()can be replaced withResponse::headers().iter(). A call toResponse::header_values(name)can be replaced withResponse::headers().get(name). -
Route collisions result in a hard error and panic.
There is no workaround. Previously, route collisions were a warning.
-
The
IntoOutcometrait has been expanded and made more flexible.There is no workaround.
IntoOutcome::into_outcome()now takes aFailurevalue to use.IntoOutcome::or_forward()was added to return aForwardoutcome ifselfindicates an error. -
The 'testing' feature was removed.
Remove
features = ["testing"]fromCargo.toml. Use the newlocalmodule for testing. -
serdewas updated to 1.0.There is no workaround. Ensure all dependencies rely on
serde1.0. -
config::active()was removed.Use
Rocket::config()to retrieve the configuration before launch. If needed, use managed state to store config information for later use. -
The
Respondertrait has changed.Responder::respond(self)was removed in favor ofResponder::respond_to(self, &Request). Responders may dynamically adjust their response based on the incoming request. -
Outcome::of(Responder)was removed whileOutcome::from(&Request, Responder)was added.Use
Outcome::from(..)instead ofOutcome::of(..). -
Usage of templates requires
Template::fairing()to be attached.Call
.attach(Template::fairing())on the application's Rocket instance before launching. -
The
Displayimplementation ofTemplatewas removed.Use
Template::show()to render a template directly. -
Request::new()is no longer exported.There is no workaround.
-
The
FromFormtrait has changed.Responder::from_form_items(&mut FormItems)was removed in favor ofResponder::from_form(&mut FormItems, bool). The second parameter indicates whether parsing should be strict (iftrue) or lenient (iffalse). -
LoggingLevelwas removed as a root reexport.It can now be imported from
rocket::config::LoggingLevel. -
An
Iovariant was added toConfigError.Ensure
matches onConfigErrorinclude anIovariant. -
ContentType::from_extension()returns anOption<ContentType>.For the old behavior, use
.unwrap_or(ContentType::Any). -
The
IntoValueconfig trait was removed in favor ofInto<Value>.There is no workaround. Use
Into<Value>as necessary. -
The
rocket_contrib::JSONtype has been renamed torocket_contrib::Json.Use
Jsoninstead ofJSON. -
All structs in the
contentmodule use TitleCase names.Use
Json,Xml,Html, andCssinstead ofJSON,XML,HTML, andCSS, respectively.
General Improvements
In addition to new features, Rocket saw the following improvements:
- "Rocket" is now capitalized in the
ServerHTTP header. - The generic parameter of
rocket_contrib::Jsondefaults tojson::Value. - The trailing '...' in the launch message was removed.
- The launch message prints regardless of the config environment.
- For debugging,
FromDatais implemented forVec<u8>andString. - The port displayed on launch is the port resolved, not the one configured.
- The
uuiddependency was updated to0.5. - The
base64dependency was updated to0.6. - The
tomldependency was updated to0.4. - The
handlebarsdependency was updated to0.27. - The
teradependency was updated to0.10. yansiis now used for all terminal coloring.- The
devrustcrelease channel is supported during builds. Configis now exported from the root.RequestimplementsCloneandDebug.- The
workersconfig parameter now defaults tonum_cpus * 2. - Console logging for table-based config values is improved.
PartialOrd,Ord, andHashare now implemented forState.- The format of a request is always logged when available.
- Route matching on
formatnow functions as documented.
Infrastructure
- All examples include a test suite.
- The
masterbranch now uses a-devversion number.
Version 0.2.8 (Jun 01, 2017)
Codegen
- Lints were updated for
2017-06-01nightly. - Minimum required
rustcis1.19.0-nightly (2017-06-01).
Version 0.2.7 (May 26, 2017)
Codegen
- Codegen was updated for
2017-05-26nightly.
Version 0.2.6 (Apr 17, 2017)
Codegen
- Allow
kandvto be used as fields inFromFormstructures by avoiding identifier collisions (#265).
Version 0.2.5 (Apr 16, 2017)
Codegen
- Lints were updated for
2017-04-15nightly. - Minimum required
rustcis1.18.0-nightly (2017-04-15).
Version 0.2.4 (Mar 30, 2017)
Codegen
- Codegen was updated for
2017-03-30nightly. - Minimum required
rustcis1.18.0-nightly (2017-03-30).
Version 0.2.3 (Mar 22, 2017)
Fixes
- Multiple header values for the same header name are now properly preserved (#223).
Core
- The
get_sliceandget_tablemethods were added toConfig. - The
pub_restrictedfeature has been stabilized!
Codegen
- Lints were updated for
2017-03-20nightly. - Minimum required
rustcis1.17.0-nightly (2017-03-22).
Infrastructure
- The test script now denies trailing whitespace.
Version 0.2.2 (Feb 26, 2017)
Codegen
- Lints were updated for
2017-02-25and2017-02-26nightlies. - Minimum required
rustcis1.17.0-nightly (2017-02-26).
Version 0.2.1 (Feb 24, 2017)
Core Fixes
Flashcookie deletion functions as expected regardless of the path.configproperly accepts IPv6 addresses.- Multiple
Set-Cookieheaders are properly set.
Core Improvements
DisplayandErrorwere implemented forConfigError.webp,ttf,otf,woff, andwoff2were added as known content types.- Routes are presorted for faster routing.
into_bytesandinto_innermethods were added toBody.
Codegen
- Fixed
unmanaged_statelint so that it works with prefilled type aliases.
Contrib
- Better errors are emitted on Tera template parse errors.
Documentation
- Fixed typos in
manageandJSONdocs.
Infrastructure
- Updated doctests for latest Cargo nightly.
Version 0.2.0 (Feb 06, 2017)
Detailed release notes for v0.2 can also be found on rocket.rs.
New Features
This release includes the following new features:
- Introduced managed state.
- Added lints that warn on unmanaged state and unmounted routes.
- Added the ability to set configuration parameters via environment variables.
Configstructures can be built viaConfigBuilder, which follows the builder pattern.- Logging can be enabled or disabled on custom configuration via a second
parameter to the
Rocket::custommethod. nameandvaluemethods were added toHeaderto retrieve the name and value of a header.- A new configuration parameter,
workers, can be used to set the number of threads Rocket uses. - The address of the remote connection is available via
Request.remote(). Request preprocessing overrides remote IP with value from theX-Real-IPheader, if present. - During testing, the remote address can be set via
MockRequest.remote(). - The
SocketAddrrequest guard retrieves the remote address. - A
UUIDtype has been added tocontrib. rocketandrocket_codegenwill refuse to build with an incompatible nightly version and emit nice error messages.- Major performance and usability improvements were upstreamed to the
cookiecrate, including the addition of aCookieBuilder. - When a checkbox isn't present in a form,
booltypes in aFromFormstructure will parse asfalse. - The
FormItemsiterator can be queried for a complete parse viacompletedandexhausted. - Routes for
OPTIONSrequests can be declared via theoptionsdecorator. - Strings can be percent-encoded via
URI::percent_encode().
Breaking Changes
This release includes several breaking changes. These changes are listed below along with a short note about how to handle the breaking change in existing applications.
-
Rocket::customtakes two parameters, the first beingConfigby value.A call in v0.1 of the form
Rocket::custom(&config)is nowRocket::custom(config, false). -
Tera templates are named without their extension.
A templated named
name.html.terais now simplyname. -
JSONunwrapmethod has been renamed tointo_inner.A call to
.unwrap()should be changed to.into_inner(). -
The
map!macro was removed in favor of thejson!macro.A call of the form
map!{ "a" => b }can be written as:json!({ "a": b }). -
The
hyper::SetCookieheader is no longer exported.Use the
Cookietype as anInto<Header>type directly. -
The
Content-TypeforStringis nowtext/plain.Use
content::HTML<String>for HTML-basedStringresponses. -
Request.content_type()returns anOption<ContentType>.Use
.unwrap_or(ContentType::Any)to get the old behavior. -
The
ContentTyperequest guard forwards when the request has noContent-Typeheader.Use an
Option<ContentType>and.unwrap_or(ContentType::Any)for the old behavior. -
A
Rocketinstance must be declared before aMockRequest.Change the order of the
rocket::ignite()andMockRequest::new()calls. -
A route with
formatspecified only matches requests with the same format.Previously, a route with a
formatwould match requests without a format specified. There is no workaround to this change; simply specify formats when required. -
FormItemscan no longer be constructed directly.Instead of constructing as
FormItems(string), construct asFormItems::from(string). -
from_from_string(&str)inFromFormremoved in favor offrom_form_items(&mut FormItems).Most implementation should be using
FormItemsinternally; simply use the passed inFormItems. In other cases, the form string can be retrieved via theinner_strmethod ofFormItems. -
Config::{set, default_for}are deprecated.Use the
set_{param}methods instead ofset, andneworbuildin place ofdefault_for. -
Route paths must be absolute.
Prepend a
/to convert a relative path into an absolute one. -
Route paths cannot contain empty segments.
Remove any empty segments, including trailing ones, from a route path.
Bug Fixes
A couple of bugs were fixed in this release:
- Handlebars partials were not properly registered (#122).
Rocket::customdid not set the custom configuration as theactiveconfiguration.- Route path segments containing more than one dynamic parameter were allowed.
General Improvements
In addition to new features, Rocket saw the following smaller improvements:
- Rocket no longer overwrites a catcher's response status.
- The
portConfigtype is now a properu16. - Clippy issues injected by codegen are resolved.
- Handlebars was updated to
0.25. - The
PartialEqimplementation ofConfigdoesn't consider the path or secret key. - Hyper dependency updated to
0.10. - The
Errortype forJSON as FromDatahas been exposed asSerdeError. - SVG was added as a known Content-Type.
- Serde was updated to
0.9. - Form parse failure now results in a 422 error code.
- Tera has been updated to
0.7. pub(crate)is used throughout to enforce visibility rules.- Query parameters in routes (
/path?<param>) are now logged. - Routes with and without query parameters no longer collide.
Infrastructure
- Testing was parallelized, resulting in 3x faster Travis builds.
Version 0.1.6 (Jan 26, 2017)
Infrastructure
- Hyper version pinned to 0.9.14 due to upstream non-semver breaking change.
Version 0.1.5 (Jan 14, 2017)
Core
- Fixed security checks in
FromSegmentsimplementation forPathBuf.
Infrastructure
proc_macrofeature removed from examples due to stability.
Version 0.1.4 (Jan 4, 2017)
Core
- Header names are treated as case-preserving.
Codegen
- Minimum supported nightly is
2017-01-03.
Version 0.1.3 (Dec 31, 2016)
Core
- Typo in
Outcomeformatting fixed (Succcess -> Success). - Added
ContentType::CSV. - Dynamic segments parameters are properly resolved, even when mounted.
- Request methods are only overridden via
_methodfield on POST. - Form value
Strings are properly decoded.
Codegen
- The
_methodfield is now properly ignored inFromFormderivation. - Unknown Content-Types in
formatno longer result in an error. - Deriving
FromFormno longer results in a deprecation warning. - Codegen will refuse to build with incompatible rustc, presenting error message and suggestion.
- Added
headas a valid decorator forHEADrequests. - Added
route(OPTIONS)as a valid decorator forOPTIONSrequests.
Contrib
- Templates with the
.teraextension are properly autoescaped. - Nested template names are properly resolved on Windows.
- Template implements
Display. - Tera dependency updated to version 0.6.
Docs
- Todo example requirements clarified in its
README.
Testing
- Tests added for
config,optional_result,optional_redirect, andquery_paramsexamples. - Testing script checks for and disallows tab characters.
Infrastructure
- New script (
bump_version.sh) automates version bumps. - Config script emits error when readlink/readpath support is bad.
- Travis badge points to public builds.
Version 0.1.2 (Dec 24, 2016)
Codegen
- Fix
get_raw_segmentsindex argument in route codegen (#41). - Segments params (
<param..>) respect prefixes.
Contrib
- Fix nested template name resolution (#42).
Infrastructure
- New script (
publish.sh) automates publishing to crates.io. - New script (
bump_version.sh) automates version bumps.
Version 0.1.1 (Dec 23, 2016)
Core
NamedFileResponderlost its body in the shuffle; it's back!
Version 0.1.0 (Dec 23, 2016)
This is the first public release of Rocket!
Breaking
All of the mentions to hyper types in core Rocket types are no more. Rocket
now implements its own Request and Response types.
ContentTypeuses associated constants instead of static methods.StatusCoderemoved in favor of newStatustype.Responsetype alias superseded byResponsetype.Responder::respondno longer takes in hyper type.Responder::respondreturnsResponse, takesselfby move.HandlerreturnsOutcomeinstead ofResponsetype alias.ErrorHandlerreturnsResult.- All
Hyper*types were moved to unprefixed versions inhyper::. MockRequest::dispatchnow returns aResponsetype.URIBufremoved in favor of unifiedURI.- Rocket panics when an illegal, dynamic mount point is used.
Core
- Rocket handles
HEADrequests automatically. - New
ResponseandResponseBuildertypes. - New
Request,Header,Status, andContentTypetypes.
Testing
MockRequestallows any type of header.MockRequestallows cookies.
Codegen
- Debug output disabled by default.
- The
ROCKET_CODEGEN_DEBUGenvironment variables enables codegen logging.
Version 0.0.11 (Dec 11, 2016)
Streaming Requests
All incoming request data is now streamed. This resulted in a major change to the Rocket APIs. They are summarized through the following API changes:
- The
formroute parameter has been removed. - The
dataroute parameter has been introduced. - Forms are now handled via the
dataparameter andFormtype. - Removed the
dataparameter fromRequest. - Added
FromDataconversion trait and default implementation. FromDatais used to automatically derive thedataparameter.Responders are now final: they cannot forward to other requests.Responders may only forward to catchers.
Breaking
- Request
uriparameter is private. Useuri()method instead. formmodule moved underrequestmodule.response::datawas renamed toresponse::content.- Introduced
OutcomewithSuccess,Failure, andForwardvariants. outcomemodule moved to top-level.Responseis now a type alias toOutcome.EmptyResponderwas removed.StatusResponderremoved in favor ofresponse::statusmodule.
Codegen
- Error handlers can now take 0, 1, or 2 parameters.
FromFormderive now works on empty structs.- Lifetimes are now properly stripped in code generation.
- Any valid ident is now allowed in single-parameter route parameters.
Core
- Route is now cloneable.
Requestno longer has any lifetime parameters.Handlertype now includes aDataparameter.httpmodule is public.Responderimplemented for()type as an empty response.- Add
config::get()for global config access. - Introduced
testingmodule. Rocket.tomlallows global configuration via[global]table.
Docs
- Added a
raw_uploadexample. - Added a
pastebinexample. - Documented all public APIs.
Testing
- Now building and running tests with
--all-featuresflag. - Added appveyor config for Windows CI testing.
Version 0.0.10 (Oct 03, 2016)
Breaking
- Remove
Rocket::newin favor ofignitemethod. - Remove
Rocket::mount_and_launchin favor of chainingmount(..).launch(). mountandcatchtakeRockettype by value.- All types related to HTTP have been moved into
httpmodule. Template::renderincontribnow takes context by reference.
Core
- Rocket now parses option
Rocket.tomlfor configuration, defaulting to sane values. ROCKET_ENVenvironment variable can be used to specify running environment.
Docs
- Document
ContentType. - Document
Request. - Add script that builds docs.
Testing
- Scripts can now be run from any directory.
- Cache Cargo directories in Travis for faster testing.
- Check that library version numbers match in testing script.
Version 0.0.9 (Sep 29, 2016)
Breaking
- Rename
response::data_typetoresponse::data.
Core
- Rocket interprets
_methodfield in forms as the incoming request's method. - Add
Outcome::Badto signify responses that failed internally. - Add a
NamedFileRespondertype that uses a file's extension for the response's content type. - Add a
StreamResponderfor streaming responses.
Contrib
- Introduce the
contribcrate. - Add JSON support via
JSON, which implementsFromRequestandResponder. - Add templating support via
Templatewhich implementsResponder.
Docs
- Initial guide-like documentation.
- Add documentation, testing, and contributing sections to README.
Testing
- Add a significant number of codegen tests.