awyr_agored
awyr_agored

Reputation: 613

How do I send data to a Racket server?

Modifying an online example I have the following code which allows a http request to be made to this Racket webserver;

#lang racket

(require web-server/servlet) 
(require web-server/servlet-env)

(define (http-response content)  
  (response/full
    200                  ; HTTP response code.
    #"OK"                ; HTTP response message.
    (current-seconds)    ; Timestamp.
    TEXT/HTML-MIME-TYPE  ; MIME type for content.
    '()                  ; Additional HTTP headers.
    (list                ; Content (in bytes) to send to the browser.
      (string->bytes/utf-8 content))))

(define (show-time-page request)
  (http-response (number->string (current-seconds))))

(define (greeting-page request)  
  (http-response (list-ref '("Hi" "Hello") (random 2))))

 (define get-data ...)

;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
  (dispatch-rules
    [("time") show-time-page]
    [("hello") greeting-page]  ; Notice this line.
    [else (error "There is no procedure to handle the url.")]))

(define (request-handler request)
  (dispatch request))

;; Start the server.
(serve/servlet
  request-handler
  #:launch-browser? #f
  #:quit? #f
  #:listen-ip "127.0.0.1"
  #:port 8001
  #:servlet-regexp #rx"")

How do I change the above code to allow it to receive data (such as a string) posted to the Racket webserver via a http-request and display it in the console? Please can you help?

Upvotes: 1

Views: 336

Answers (1)

Greg Hendershott
Greg Hendershott

Reputation: 16260

Define a request handler for the POST request. Have it extract the posted data from the request:

(define (example-post request)
  (define data (request-post-data/raw request))
  (define str (format "got post data: ~v" data))
  (displayln str)
  (http-response str))

Add the handler to dispatch-rules. Be sure to specify it's handling a POST (not the default GET) request:

;; URL routing table (URL dispatcher).
(define-values (dispatch generate-url)
  (dispatch-rules
    [("time") show-time-page]
    [("hello") greeting-page]
    [("example-post") #:method "post" example-post] ; <=== NEW
    [else (error "There is no procedure to handle the url.")]))

Now, in a shell if you do

curl --data "hi" http://127.0.0.1:8001/example-post

it will show the response data got post data: #"hi" --- as will the Racket console.

Upvotes: 4

Related Questions