Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server::respond_with_static_file() for better control over static files #1927

Closed

Conversation

paulharris
Copy link
Contributor

Alternative approach to #1906
This approach allows library user to still get the benefits of httplib, in particular the valid_path() check and the directory redirect.
The current fix set_file_content() is good but skips those things.
Plus, it segfaults when I ask it to set_file_content(a directory).


Can now handle static file requests the same as any Get() request, meaning the handler's priority can be controlled by the developer.

ie
svr.Get("/something", [](auto req, auto res) {
dont return the file "something";
instead, return something else;
});

svr.GET("/(.*)", [](auto req, auto res) {
// chance to further filter or adjust request to suit
auto result = svr.respond_with_static_file(
req, res, req.matches[1], "base_dir");
// optional chance to override response from the default
switch (result) {
SFR_DirRedirect: break;
SFR_File: break; // chance to set additional headers
SFR_CouldNotOpen: break; // chance to respond nicely
SFR_NotFound: break; // chance to respond nicely
}
});

Can now handle static file requests the same as any Get() request,
meaning the handler's priority can be controlled by the developer.

ie
svr.Get("/something", [](auto req, auto res) {
  dont return the file "something";
  instead, return something else;
});

svr.GET("/(.*)", [](auto req, auto res) {
  // chance to further filter or adjust request to suit
  auto result = svr.respond_with_static_file(
                        req, res, req.matches[1], "base_dir");
  // optional chance to override response from the default
  switch (result) {
     SFR_DirRedirect:  break;
     SFR_File:         break; // chance to set additional headers
     SFR_CouldNotOpen: break; // chance to respond nicely
     SFR_NotFound:     break; // chance to respond nicely
  }
});
@paulharris
Copy link
Contributor Author

Oh I forgot to mention my solution requires svr, captured in the lambda.
So I don't like the solution, I think yours is better, it just needs to add more smarts.

I've made another PR to consider.

In the end, with mmap() problems, I've now switched to doing it all in the client code and using fread.

@yhirose
Copy link
Owner

yhirose commented Sep 9, 2024

Same #1932. Thanks for your understanding!

@yhirose yhirose closed this Sep 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants