pub enum Encoding {
    Gzip,
    Br,
}
Expand description

Type of response encoding.

Variants§

§

Gzip

Response body is encoded with gzip.

§

Br

Response body is encoded with brotli.

Implementations§

Create a HeaderValue for this encoding.

Examples found in repository?
src/util/file_response_builder.rs (line 264)
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
    pub fn build<F: IntoFileAccess>(
        &self,
        file: ResolvedFile<F>,
    ) -> Result<Response<Body<F::Output>>> {
        let mut res = ResponseBuilder::new();

        // Set `Last-Modified` and check `If-Modified-Since`.
        let modified = file.modified.filter(|v| {
            v.duration_since(UNIX_EPOCH)
                .ok()
                .filter(|v| v >= &MIN_VALID_MTIME)
                .is_some()
        });

        // default to false when specified, either the etag or last_modified will set
        // it to true later.
        let mut range_cond_ok = self.if_range.is_none();
        if let Some(modified) = modified {
            if let Ok(modified_unix) = modified.duration_since(UNIX_EPOCH) {
                // Compare whole seconds only, because the HTTP date-time
                // format also does not contain a fractional part.
                if let Some(Ok(ims_unix)) =
                    self.if_modified_since.map(|v| v.duration_since(UNIX_EPOCH))
                {
                    if modified_unix.as_secs() <= ims_unix.as_secs() {
                        return ResponseBuilder::new()
                            .status(StatusCode::NOT_MODIFIED)
                            .body(Body::Empty);
                    }
                }

                let etag = format!(
                    "W/\"{0:x}-{1:x}.{2:x}\"",
                    file.size,
                    modified_unix.as_secs(),
                    modified_unix.subsec_nanos()
                );
                if let Some(ref v) = self.if_range {
                    if *v == etag {
                        range_cond_ok = true;
                    }
                }

                res = res.header(header::ETAG, etag);
            }

            let last_modified_formatted = httpdate::fmt_http_date(modified);
            if let Some(ref v) = self.if_range {
                if *v == last_modified_formatted {
                    range_cond_ok = true;
                }
            }

            res = res
                .header(header::LAST_MODIFIED, last_modified_formatted)
                .header(header::ACCEPT_RANGES, "bytes");
        }

        // Build remaining headers.
        if let Some(seconds) = self.cache_headers {
            res = res.header(
                header::CACHE_CONTROL,
                format!("public, max-age={}", seconds),
            );
        }

        if self.is_head {
            res = res.header(header::CONTENT_LENGTH, format!("{}", file.size));
            return res.status(StatusCode::OK).body(Body::Empty);
        }

        let ranges = self.range.as_ref().filter(|_| range_cond_ok).and_then(|r| {
            match HttpRange::parse(r, file.size) {
                Ok(r) => Some(Ok(r)),
                Err(HttpRangeParseError::NoOverlap) => Some(Err(())),
                Err(HttpRangeParseError::InvalidRange) => None,
            }
        });

        if let Some(ranges) = ranges {
            let ranges = match ranges {
                Ok(r) => r,
                Err(()) => {
                    return res
                        .status(StatusCode::RANGE_NOT_SATISFIABLE)
                        .body(Body::Empty);
                }
            };

            if ranges.len() == 1 {
                let single_span = ranges[0];
                res = res
                    .header(
                        header::CONTENT_RANGE,
                        content_range_header(&single_span, file.size),
                    )
                    .header(header::CONTENT_LENGTH, format!("{}", single_span.length));

                let body_stream =
                    FileBytesStreamRange::new(file.handle.into_file_access(), single_span);
                return res
                    .status(StatusCode::PARTIAL_CONTENT)
                    .body(Body::Range(body_stream));
            } else if ranges.len() > 1 {
                let mut boundary_tmp = [0u8; BOUNDARY_LENGTH];

                let mut rng = thread_rng();
                for v in boundary_tmp.iter_mut() {
                    // won't panic since BOUNDARY_CHARS is non-empty
                    *v = *BOUNDARY_CHARS.choose(&mut rng).unwrap();
                }

                // won't panic because boundary_tmp is guaranteed to be all ASCII
                let boundary = std::str::from_utf8(&boundary_tmp[..]).unwrap().to_string();

                res = res.header(
                    hyper::header::CONTENT_TYPE,
                    format!("multipart/byteranges; boundary={}", boundary),
                );

                let mut body_stream = FileBytesStreamMultiRange::new(
                    file.handle.into_file_access(),
                    ranges,
                    boundary,
                    file.size,
                );
                if let Some(content_type) = file.content_type.as_ref() {
                    body_stream.set_content_type(content_type);
                }

                res = res.header(
                    hyper::header::CONTENT_LENGTH,
                    format!("{}", body_stream.compute_length()),
                );

                return res
                    .status(StatusCode::PARTIAL_CONTENT)
                    .body(Body::MultiRange(body_stream));
            }
        }

        res = res.header(header::CONTENT_LENGTH, format!("{}", file.size));
        if let Some(content_type) = file.content_type {
            res = res.header(header::CONTENT_TYPE, content_type);
        }
        if let Some(encoding) = file.encoding {
            res = res.header(header::CONTENT_ENCODING, encoding.to_header_value());
        }

        // Stream the body.
        res.status(StatusCode::OK)
            .body(Body::Full(FileBytesStream::new_with_limit(
                file.handle.into_file_access(),
                file.size,
            )))
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more