Files
pheynnx_site/server.odin
T
2026-08-04 21:23:11 -07:00

103 lines
2.4 KiB
Odin

package pheynnx
import "core:fmt"
import "core:log"
import "core:net"
import "core:os"
import "core:path/filepath"
import "core:strings"
import http "submodules/odin-http"
foreign import goldmark "libgoldmark.lib"
foreign goldmark {
MarkdownToHTML :: proc(source: cstring) -> cstring ---
FreeString :: proc(s: cstring) ---
}
State :: struct {
num: int,
global_css: string,
import_html: cstring,
}
state := State {
num = 1,
}
main :: proc() {
markdown, err1 := os.read_entire_file_from_path("test.markdown", context.temp_allocator)
src_c := strings.clone_to_cstring(string(markdown))
result_c := MarkdownToHTML(src_c)
defer FreeString(result_c)
defer delete(src_c)
state.import_html = result_c
context.logger = log.create_console_logger(.Info)
data, err2 := os.read_entire_file_from_path("styles/main.css", context.temp_allocator)
state.global_css = string(data)
s: http.Server
http.server_shutdown_on_interrupt(&s)
router: http.Router
http.router_init(&router)
defer http.router_destroy(&router)
root_routes(&router)
http.route_get(&router, "/static/(.*)", proc() -> http.Handler {
return http.Handler {
handle = proc(handler: ^http.Handler, req: ^http.Request, res: ^http.Response) {
rel_path := strings.trim_prefix(req.url.path, "/static/")
full_path, _ := filepath.join({"web/static", rel_path})
defer delete(full_path)
info, err := os.stat(full_path, context.temp_allocator)
if err != os.ERROR_NONE || info.type == .Directory {
http.respond(res, http.Status.Not_Found)
return
}
http.respond_dir(res, "/static/", "web/static", req.url.path)
free_all(context.temp_allocator)
},
}
}())
routed := http.router_handler(&router)
err := http.listen_and_serve(&s, routed, net.Endpoint{address = net.IP4_Loopback, port = 6969})
fmt.assertf(err == nil, "server stopped with error: %v", err)
free_all(context.temp_allocator)
}
// ROUTERS
root_routes :: proc(r: ^http.Router) {
http.route_get(r, "/one", one_handler())
http.route_get(r, "/two", http.handler(two_handler))
}
// HANDLERS
one_handler :: proc() -> http.Handler {
return http.Handler {
handle = proc(handler: ^http.Handler, req: ^http.Request, res: ^http.Response) {
state.num += 1
http.respond_html(res, render_index_page(&state))
},
}
}
two_handler :: proc(req: ^http.Request, res: ^http.Response) {
state.num *= 2
http.respond_html(res, render_index_page(&state))
}