AtlatestRepositorysigil-http
sigil-http / tree / examplessimple-server.sgl
1
;;; Test HTTP Server2
;;;3
;;; Run with:4
;;; ./build/bin/sgl-boot packages/sigil-http/test/test-server.sgl5
;;;6
;;; Then test with:7
;;; curl http://localhost:8080/8
;;; curl http://localhost:8080/hello9
;;; curl http://localhost:8080/json11
;; Test: import directly from sub-modules instead of umbrella12
(import (sigil http request)13
(sigil http response)14
(sigil http server)15
(sigil string))17
(define (handler request)18
(let ((path (http-request-path request))19
(method (http-request-method request)))20
(display (string-append (symbol->string method) " " path "\n"))21
(cond22
;; Root path23
((string=? path "/")24
(http-response/html HTTP-OK25
"<!DOCTYPE html>26
<html>27
<head><title>Sigil HTTP Test</title></head>28
<body>29
<h1>Hello from Sigil HTTP!</h1>30
<p>Try these endpoints:</p>31
<ul>32
<li><a href='/hello'>/hello</a> - Plain text</li>33
<li><a href='/json'>/json</a> - JSON response</li>34
<li><a href='/echo'>/echo</a> - Echo request info</li>35
</ul>36
</body>37
</html>"))39
;; Plain text40
((string=? path "/hello")41
(http-response/text HTTP-OK "Hello, World!"))43
;; JSON44
((string=? path "/json")45
(http-response/json HTTP-OK46
"{\"message\": \"Hello from Sigil!\", \"status\": \"ok\"}"))48
;; Echo request info49
((string=? path "/echo")50
(http-response/text HTTP-OK51
(string-append52
"Method: " (symbol->string method) "\n"53
"Path: " path "\n"54
"Query: " (or (http-request-query request) "(none)") "\n"55
"Headers:\n"56
(headers->string (http-request-headers request)))))58
;; Not found59
(else60
(http-response/not-found)))))62
(define (headers->string headers)63
(let loop ((entries (dict-entries headers)) (result ""))64
(if (null? entries)65
result66
(let ((h (car entries)))67
(loop (cdr entries)68
(string-append result69
" " (keyword->string (car h)) ": " (cdr h) "\n"))))))71
(display "Starting test server on port 8080...\n")72
(display "Press Ctrl+C to stop.\n\n")74
(http-serve handler port: 8080)