Skip to content

Instantly share code, notes, and snippets.

@hholst80
Created February 24, 2024 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hholst80/c3b802c92b6b7179a0057c7cc0811b95 to your computer and use it in GitHub Desktop.
Save hholst80/c3b802c92b6b7179a0057c7cc0811b95 to your computer and use it in GitHub Desktop.
module main
/*
In-memory blob service.
PUT /path/to/file save a blob under the given path
will overwrite any previously stored blob
GET /path/to/file load a blob from the given path
returns 404 if no previous blob saved
*/
import net.http { CommonHeader, Request, Response, Server }
struct Blob {
content_type string
data string
}
struct BlobHandler {
mut:
files map[string]Blob
}
fn (mut h BlobHandler) handle(req Request) Response {
mut res := Response{
header: http.new_header_from_map({
CommonHeader.content_type: "text/plain"
})
}
if req.method == .put {
content_type := req.header.get(.content_type) or { "application/json" }
h.files[req.url] = Blob{ content_type: content_type, data: req.data }
res.status_code = 200
return res
}
if req.method != .get {
res.status_code = 405
res.body = "Error: method not supported\r\n"
return res
}
if req.url !in h.files {
res.status_code = 404
res.body = "Error: blob not found\r\n"
return res
}
blob := h.files[req.url]
res.status_code = 200
res.header.set(.content_type, blob.content_type)
res.body = blob.data
return res
}
fn main() {
mut server := Server{
handler: BlobHandler{}
}
server.listen_and_serve()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment