Add the ability to specify a lang parameter

This commit is contained in:
Michael Lazar 2020-06-07 23:03:25 -04:00
parent 961d42e3e2
commit a871b6017d
3 changed files with 33 additions and 2 deletions

View File

@ -1,5 +1,14 @@
# Jetforce Changelog
### Unreleased
#### Features
- Added a ``--default-lang`` command line argument to the static file server.
This setting will define a language parameter that will be attached to the
meta for all text/gemini responses. For example, ``--default-lang=en`` will
set the response meta to ``"text/gemini; lang=en"``.
### v0.3.2
#### Bugfixes

View File

@ -92,6 +92,13 @@ group.add_argument(
dest="index_file",
)
group.add_argument(
"--default-lang",
help="A lang parameter that will be indicated in the response meta",
default=None,
dest="default_lang",
)
def main():
args = parser.parse_args()
@ -99,6 +106,7 @@ def main():
root_directory=args.root_directory,
index_file=args.index_file,
cgi_directory=args.cgi_directory,
default_lang=args.default_lang,
)
server = GeminiServer(
app=app,

View File

@ -28,12 +28,14 @@ class StaticDirectoryApplication(JetforceApplication):
root_directory: str = "/var/gemini",
index_file: str = "index.gmi",
cgi_directory: str = "cgi-bin",
default_lang: typing.Optional[str] = None,
):
super().__init__()
self.routes.append((RoutePattern(), self.serve_static_file))
self.root = pathlib.Path(root_directory).resolve(strict=True)
self.cgi_directory = cgi_directory.strip("/") + "/"
self.default_lang = default_lang
self.index_file = index_file
self.mimetypes = mimetypes.MimeTypes()
@ -99,6 +101,7 @@ class StaticDirectoryApplication(JetforceApplication):
if filesystem_path.is_file():
mimetype = self.guess_mimetype(filesystem_path.name)
mimetype = self.add_extra_parameters(mimetype)
generator = self.load_file(filesystem_path)
return Response(Status.SUCCESS, mimetype, generator)
@ -111,11 +114,13 @@ class StaticDirectoryApplication(JetforceApplication):
index_file = filesystem_path / self.index_file
if index_file.exists():
mimetype = self.add_extra_parameters("text/gemini")
generator = self.load_file(index_file)
return Response(Status.SUCCESS, "text/gemini", generator)
return Response(Status.SUCCESS, mimetype, generator)
mimetype = self.add_extra_parameters("text/gemini")
generator = self.list_directory(url_path, filesystem_path)
return Response(Status.SUCCESS, "text/gemini", generator)
return Response(Status.SUCCESS, mimetype, generator)
else:
return Response(Status.NOT_FOUND, "Not Found")
@ -191,6 +196,15 @@ class StaticDirectoryApplication(JetforceApplication):
else:
return mime or "text/plain"
def add_extra_parameters(self, meta: str) -> str:
"""
Attach extra parameters to the response meta string.
"""
if self.default_lang is not None:
if meta.startswith("text/gemini"):
meta += f"; lang={self.default_lang}"
return meta
def default_callback(self, request: Request, **_) -> Response:
"""
Since the StaticDirectoryApplication only serves gemini URLs, return