pub struct AcceptEncoding {
    pub gzip: bool,
    pub br: bool,
}
Expand description

Flags for which encodings to resolve.

Fields§

§gzip: bool

Look for .gz files.

§br: bool

Look for .br files.

Implementations§

Return an AcceptEncoding with all flags set.

Return an AcceptEncoding with no flags set.

Examples found in repository?
src/resolve.rs (line 110)
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
    pub fn with_opener(opener: O) -> Self {
        Self {
            opener: Arc::new(opener),
            allowed_encodings: AcceptEncoding::none(),
        }
    }

    /// Resolve the request by trying to find the file in the root.
    ///
    /// The returned future may error for unexpected IO errors, passing on the `std::io::Error`.
    /// Certain expected IO errors are handled, though, and simply reflected in the result. These are
    /// `NotFound` and `PermissionDenied`.
    pub async fn resolve_request<B>(
        &self,
        req: &Request<B>,
    ) -> Result<ResolveResult<O::File>, IoError> {
        // Handle only `GET`/`HEAD` and absolute paths.
        match *req.method() {
            Method::HEAD | Method::GET => {}
            _ => {
                return Ok(ResolveResult::MethodNotMatched);
            }
        }

        // Parse `Accept-Encoding` header.
        let accept_encoding = self.allowed_encodings
            & req
                .headers()
                .get(header::ACCEPT_ENCODING)
                .map(AcceptEncoding::from_header_value)
                .unwrap_or(AcceptEncoding::none());

        self.resolve_path(req.uri().path(), accept_encoding).await
    }

    /// Resolve the request path by trying to find the file in the given root.
    ///
    /// The returned future may error for unexpected IO errors, passing on the `std::io::Error`.
    /// Certain expected IO errors are handled, though, and simply reflected in the result. These are
    /// `NotFound` and `PermissionDenied`.
    ///
    /// Note that, unlike `resolve_request`, it is up to the caller to check the request method and
    /// optionally the 'Accept-Encoding' header.
    pub async fn resolve_path(
        &self,
        request_path: &str,
        accept_encoding: AcceptEncoding,
    ) -> Result<ResolveResult<O::File>, IoError> {
        // Sanitize input path.
        let RequestedPath {
            sanitized: mut path,
            is_dir_request,
        } = RequestedPath::resolve(request_path);

        // Try to open the file.
        let file = match self.opener.open(&path).await {
            Ok(pair) => pair,
            Err(err) => return map_open_err(err),
        };

        // The resolved path doesn't contain the trailing slash anymore, so we may
        // have opened a file for a directory request, which we treat as 'not found'.
        if is_dir_request && !file.is_dir {
            return Ok(ResolveResult::NotFound);
        }

        // We may have opened a directory for a file request, in which case we redirect.
        if !is_dir_request && file.is_dir {
            // Build the redirect path. On Windows, we can't just append the entire path, because
            // it contains Windows path separators. Instead, append each component separately.
            let mut target = String::with_capacity(path.as_os_str().len() + 2);
            target.push('/');
            for component in path.components() {
                target.push_str(&component.as_os_str().to_string_lossy());
                target.push('/');
            }

            return Ok(ResolveResult::IsDirectory {
                redirect_to: target,
            });
        }

        // If not a directory, serve this file.
        if !is_dir_request {
            return self.resolve_final(file, path, accept_encoding).await;
        }

        // Resolve the directory index.
        path.push("index.html");
        let file = match self.opener.open(&path).await {
            Ok(pair) => pair,
            Err(err) => return map_open_err(err),
        };

        // The directory index cannot itself be a directory.
        if file.is_dir {
            return Ok(ResolveResult::NotFound);
        }

        // Serve this file.
        self.resolve_final(file, path, accept_encoding).await
    }

    // Found a file, perform final resolution steps.
    async fn resolve_final(
        &self,
        file: FileWithMetadata<O::File>,
        path: PathBuf,
        accept_encoding: AcceptEncoding,
    ) -> Result<ResolveResult<O::File>, IoError> {
        // Determine MIME-type. This needs to happen before we resolve a pre-encoded file.
        let mime = MimeGuess::from_path(&path)
            .first()
            .map(|mime| mime.to_string());

        // Resolve pre-encoded files.
        if accept_encoding.br {
            let mut br_path = path.clone().into_os_string();
            br_path.push(".br");
            if let Ok(file) = self.opener.open(br_path.as_ref()).await {
                return Ok(ResolveResult::Found(ResolvedFile::new(
                    file,
                    mime,
                    Some(Encoding::Br),
                )));
            }
        }
        if accept_encoding.gzip {
            let mut gzip_path = path.into_os_string();
            gzip_path.push(".gz");
            if let Ok(file) = self.opener.open(gzip_path.as_ref()).await {
                return Ok(ResolveResult::Found(ResolvedFile::new(
                    file,
                    mime,
                    Some(Encoding::Gzip),
                )));
            }
        }

        // No pre-encoded file found, serve the original.
        Ok(ResolveResult::Found(ResolvedFile::new(file, mime, None)))
    }
}

impl<O> Clone for Resolver<O> {
    fn clone(&self) -> Self {
        Self {
            opener: self.opener.clone(),
            allowed_encodings: self.allowed_encodings,
        }
    }
}

/// Type of response encoding.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Encoding {
    /// Response body is encoded with gzip.
    Gzip,
    /// Response body is encoded with brotli.
    Br,
}

impl Encoding {
    /// Create a `HeaderValue` for this encoding.
    pub fn to_header_value(&self) -> HeaderValue {
        HeaderValue::from_static(match self {
            Encoding::Gzip => "gzip",
            Encoding::Br => "br",
        })
    }
}

/// Flags for which encodings to resolve.
#[derive(Debug, Copy, Clone)]
pub struct AcceptEncoding {
    /// Look for `.gz` files.
    pub gzip: bool,
    /// Look for `.br` files.
    pub br: bool,
}

impl AcceptEncoding {
    /// Return an `AcceptEncoding` with all flags set.
    pub const fn all() -> Self {
        Self {
            gzip: true,
            br: true,
        }
    }

    /// Return an `AcceptEncoding` with no flags set.
    pub const fn none() -> Self {
        Self {
            gzip: false,
            br: false,
        }
    }

    /// Fill an `AcceptEncoding` struct from a header value.
    pub fn from_header_value(value: &HeaderValue) -> Self {
        let mut res = Self::none();
        if let Ok(value) = value.to_str() {
            for enc in value.split(',') {
                // TODO: Handle weights (q=)
                match enc.split(';').next().unwrap().trim() {
                    "gzip" => res.gzip = true,
                    "br" => res.br = true,
                    _ => {}
                }
            }
        }
        res
    }

Fill an AcceptEncoding struct from a header value.

Trait Implementations§

The resulting type after applying the & operator.
Performs the & operation. Read more
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

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