main.seq
seq
# Seq Demo - HTTP Server with Static Files
# Runs on port 5000
: http-html ( String -- String )
  dup string-length int->string
  "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: " swap string-concat
  "\r\n\r\n" string-concat
  swap string-concat
;
: http-ok ( String -- String )
  dup string-length int->string
  "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: " swap string-concat
  "\r\n\r\n" string-concat
  swap string-concat
;
: http-json ( String -- String )
  dup string-length int->string
  "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " swap string-concat
  "\r\n\r\n" string-concat
  swap string-concat
;
: http-not-found ( String -- String )
  dup string-length int->string
  "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: " swap string-concat
  "\r\n\r\n" string-concat
  swap string-concat
;
: http-request-line ( String -- String )
  "\r\n" string-split
  0 variant-field-at
;
: http-request-path ( String -- String )
  http-request-line
  " " string-split
  1 variant-field-at
;
: string-suffix-after ( String String -- String )
  over over string-starts-with if
    string-split
    dup variant-field-count 2 < if
      drop drop ""
    else
      1 variant-field-at
    then
  else
    drop drop ""
  then
;
: http-path-suffix ( String String -- String )
  swap http-request-path
  swap string-suffix-after
;
: serve-index ( -- String )
  "static/index.html" file-slurp http-html
;
: serve-404 ( -- String )
  "static/404.html" file-slurp http-not-found
;
: route ( String -- String )
  dup "GET / " string-starts-with if
    drop serve-index
  else
    dup "GET /health" string-starts-with if
      drop "OK" http-ok
    else
      dup "GET /api/status" string-starts-with if
        drop "{\"status\":\"running\",\"language\":\"seq\",\"port\":5000}" http-json
      else
        dup "GET /echo/" string-starts-with if
          "/echo/" http-path-suffix
          "You said: " swap string-concat
          http-ok
        else
          drop serve-404
        then
      then
    then
  then
;
: handle-connection ( Int -- )
  dup
  tcp-read
  route
  over
  tcp-write
  tcp-close
;
: worker ( Int -- )
  receive
  handle-connection
;
: accept-loop ( Int -- )
  dup tcp-accept
  make-channel
  dup [ worker ] spawn
  drop drop
  send
  accept-loop
;
: main ( -- )
  "Seq Demo HTTP Server" write_line
  "Port: 8080 (socat forwards 5000->8080)" write_line
  "Routes: / /health /api/status /echo/:msg" write_line
  8080 tcp-listen
  "Listening..." write_line
  accept-loop
;
No comments yet.