Lightbug is a simple and sweet HTTP framework for Mojo that builds on best practice from systems programming, such as the Golang FastHTTP and Rust may_minihttp.
This is not production ready yet. We're aiming to keep up with new developments in Mojo, but it might take some time to get to a point when this is safe to use in real-world applications.
Lightbug currently has the following features:
- Pure Mojo networking! No dependencies on Python by default
- TCP-based server and client implementation
- Assign your own custom handler to a route
- Craft HTTP requests and responses with built-in primitives
- Everything is fully typed, with no
def
functions used
- Logging - @toasty/stump
- CLI and Terminal - @toasty/prism, @toasty/mog
- Date/Time - @mojoto/morrow and @toasty/small-time
The only hard dependency for lightbug_http
is Mojo.
Learn how to get up and running with Mojo on the Modular website.
Once you have a Mojo project set up locally,
- Add the
mojo-community
channel to yourmojoproject.toml
, e.g:[project] channels = ["conda-forge", "https://conda.modular.com/max", "https://repo.prefix.dev/mojo-community"]
- Add
lightbug_http
as a dependency:[dependencies] lightbug_http = ">=0.1.5"
- Run
magic install
at the root of your project, wheremojoproject.toml
is located - Lightbug should now be installed as a dependency. You can import all the default imports at once, e.g:
or import individual structs and functions, e.g.
from lightbug_http import *
there are some default handlers you can play with:from lightbug_http.service import HTTPService from lightbug_http.http import HTTPRequest, HTTPResponse, OK, NotFound
from lightbug_http.service import Printer # prints request details to console from lightbug_http.service import Welcome # serves an HTML file with an image (currently requires manually adding files to static folder, details below) from lightbug_http.service import ExampleRouter # serves /, /first, /second, and /echo routes
- Add your handler in
lightbug.π₯
by passing a struct that satisfies the following trait:For example, to make atrait HTTPService: fn func(self, req: HTTPRequest) raises -> HTTPResponse: ...
Printer
service that prints some details about the request to console:from lightbug_http import * @value struct Printer(HTTPService): fn func(self, req: HTTPRequest) raises -> HTTPResponse: var uri = req.uri print("Request URI: ", to_string(uri.request_uri)) var header = req.headers print("Request protocol: ", req.protocol) print("Request method: ", req.method) print( "Request Content-Type: ", to_string(header[HeaderKey.CONTENT_TYPE]) ) var body = req.body_raw print("Request Body: ", to_string(body)) return OK(body)
- Start a server listening on a port with your service like so.
from lightbug_http import Welcome, Server fn main() raises: var server = Server() var handler = Welcome() server.listen_and_serve("0.0.0.0:8080", handler)
Feel free to change the settings in listen_and_serve()
to serve on a particular host and port.
Now send a request 0.0.0.0:8080
. You should see some details about the request printed out to the console.
Congrats π₯³ You're using Lightbug!
Routing is not in scope for this library, but you can easily set up routes yourself:
from lightbug_http import *
@value
struct ExampleRouter(HTTPService):
fn func(self, req: HTTPRequest) raises -> HTTPResponse:
var body = req.body_raw
var uri = req.uri
if uri.path == "/":
print("I'm on the index path!")
if uri.path == "/first":
print("I'm on /first!")
elif uri.path == "/second":
print("I'm on /second!")
elif uri.path == "/echo":
print(to_string(body))
return OK(body)
We plan to add more advanced routing functionality in a future library called lightbug_api
, see Roadmap for more details.
The default welcome screen shows an example of how to serve files like images or HTML using Lightbug. Mojo has built-in open
, read
and read_bytes
methods that you can use to read files and serve them on a route. Assuming you copy an html file and image from the Lightbug repo into a static
directory at the root of your repo:
from lightbug_http import *
@value
struct Welcome(HTTPService):
fn func(self, req: HTTPRequest) raises -> HTTPResponse:
var uri = req.uri
if uri.path == "/":
var html: Bytes
with open("static/lightbug_welcome.html", "r") as f:
html = f.read_bytes()
return OK(html, "text/html; charset=utf-8")
if uri.path == "/logo.png":
var image: Bytes
with open("static/logo.png", "r") as f:
image = f.read_bytes()
return OK(image, "image/png")
return NotFound(uri.path)
Create a file, e.g client.mojo
with the following code. Run magic run mojo client.mojo
to execute the request to a given URL.
from lightbug_http import *
from lightbug_http.client import Client
fn test_request(inout client: Client) raises -> None:
var uri = URI.parse_raises("http://httpbin.org/status/404")
var headers = Header("Host", "httpbin.org")
var request = HTTPRequest(uri, headers)
var response = client.do(request^)
# print status code
print("Response:", response.status_code)
# print parsed headers (only some are parsed for now)
print("Content-Type:", response.headers["Content-Type"])
print("Content-Length", response.headers["Content-Length"])
print("Server:", to_string(response.headers["Server"]))
print(
"Is connection set to connection-close? ", response.connection_close()
)
# print body
print(to_string(response.body_raw))
fn main() -> None:
try:
var client = Client()
test_request(client)
except e:
print(e)
Pure Mojo-based client is available by default. This client is also used internally for testing the server.
By default, Lightbug uses the pure Mojo implementation for networking. To use Python's socket
library instead, just import the PythonServer
instead of the Server
with the following line:
from lightbug_http.python.server import PythonServer
You can then use all the regular server commands in the same way as with the default server.
Note: as of September, 2024, PythonServer
and PythonClient
throw a compilation error when starting. There's an open issue to fix this - contributions welcome!
We're working on support for the following (contributors welcome!):
- WebSocket Support
- SSL/HTTPS support
- UDP support
- Better error handling, improved form/multipart and JSON support
- Multiple simultaneous connections, parallelization and performance optimizations
- HTTP 2.0/3.0 support
- ASGI spec conformance
The plan is to get to a feature set similar to Python frameworks like Starlette, but with better performance.
Our vision is to develop three libraries, with lightbug_http
(this repo) as a starting point:
lightbug_http
- HTTP infrastructure and basic API developmentlightbug_api
- (coming later in 2024!) Tools to make great APIs fast, with support for OpenAPI spec and domain driven designlightbug_web
- (release date TBD) Full-stack web framework for Mojo, similar to NextJS or SvelteKit
The idea is to get to a point where the entire codebase of a simple modern web application can be written in Mojo.
We don't make any promises, though -- this is just a vision, and whether we get there or not depends on many factors, including the support of the community.
See the open issues and submit your own to help drive the development of Lightbug.
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated. See CONTRIBUTING.md for more details on how to contribute.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
Distributed under the MIT License. See LICENSE.txt
for more information.
Project Link: https://github.com/saviorand/mojo-web
We were drawing a lot on the following projects:
- FastHTTP (Golang)
- may_minihttp (Rust)
- FireTCP (One of the earliest Mojo TCP implementations!)
Want your name to show up here? See CONTRIBUTING.md!
Made with contrib.rocks.