AtlatestRepositorysigil-http

sigil-http / tree / examplessimple-server.sgl

1;;; Test HTTP Server
2;;;
3;;; Run with:
4;;; ./build/bin/sgl-boot packages/sigil-http/test/test-server.sgl
5;;;
6;;; Then test with:
7;;; curl http://localhost:8080/
8;;; curl http://localhost:8080/hello
9;;; curl http://localhost:8080/json
11;; Test: import directly from sub-modules instead of umbrella
12(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 (cond
22 ;; Root path
23 ((string=? path "/")
24 (http-response/html HTTP-OK
25 "<!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 text
40 ((string=? path "/hello")
41 (http-response/text HTTP-OK "Hello, World!"))
43 ;; JSON
44 ((string=? path "/json")
45 (http-response/json HTTP-OK
46 "{\"message\": \"Hello from Sigil!\", \"status\": \"ok\"}"))
48 ;; Echo request info
49 ((string=? path "/echo")
50 (http-response/text HTTP-OK
51 (string-append
52 "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 found
59 (else
60 (http-response/not-found)))))
62(define (headers->string headers)
63 (let loop ((entries (dict-entries headers)) (result ""))
64 (if (null? entries)
65 result
66 (let ((h (car entries)))
67 (loop (cdr entries)
68 (string-append result
69 " " (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)