Skip to content

Instantly share code, notes, and snippets.

@yrashk
Last active March 23, 2023 03: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 yrashk/4ff1df5565a4694f8cefb49c16d306c0 to your computer and use it in GitHub Desktop.
Save yrashk/4ff1df5565a4694f8cefb49c16d306c0 to your computer and use it in GitHub Desktop.
A micro web app example for Omnigres (https://github.com/omnigres/omnigres) (README.md candidate)
create table if not exists motd
(
id int primary key generated always as identity,
content text,
posted_at timestamp default now()
);
create or replace function show_motd() returns setof omni_httpd.http_response as
$$
select
omni_httpd.http_response(body => 'Posted at ' || posted_at || E'\n' || content)
from
motd
order by
posted_at desc
limit 1;
$$ language sql;
create or replace function no_motd() returns setof omni_httpd.http_response as
$$
select omni_httpd.http_response(body => 'No MOTD');
$$
language sql;
create or replace function update_motd(request omni_httpd.http_request) returns omni_httpd.http_response as
$$
insert
into
motd (content)
values
(convert_from(request.body, 'UTF8'))
returning omni_httpd.http_response(status => 201);
$$
language sql;
update omni_httpd.handlers
set
query = (select
omni_httpd.cascading_query(name, query order by priority desc nulls last)
from
(values
('show', $$select show_motd() from request where request.method = 'GET'$$, 1),
('update', $$select update_motd(request.*) from request where request.method = 'POST'$$, 1),
('fallback', $$select no_motd() from request where request.method = 'GET'$$,
0)) handlers(name, query, priority));
$ http GET localhost:8080
HTTP/1.1 200 OK
Connection: keep-alive
Server: omni_httpd-0.1
content-type: text/plain; charset=utf-8
transfer-encoding: chunked
No MOTD
$ http localhost:8080 --raw "Check out Omnigres"
HTTP/1.1 201 OK
Connection: keep-alive
Server: omni_httpd-0.1
transfer-encoding: chunked
$ http localhost:8080
HTTP/1.1 200 OK
Connection: keep-alive
Server: omni_httpd-0.1
content-type: text/plain; charset=utf-8
transfer-encoding: chunked
Posted at 2023-03-23 02:59:14.679113
Check out Omnigres
$ http localhost:8080 --raw "First release is coming"
HTTP/1.1 201 OK
Connection: keep-alive
Server: omni_httpd-0.1
transfer-encoding: chunked
$ http localhost:8080
HTTP/1.1 200 OK
Connection: keep-alive
Server: omni_httpd-0.1
content-type: text/plain; charset=utf-8
transfer-encoding: chunked
Posted at 2023-03-23 02:59:28.771903
First release is coming
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment