Search code examples
getschemeracket

How do you access get parameters in racket server application


I have a project in my Organization of Programming Languages course and am building a web API using Racket. I have managed to get a server up and running that has multiple landing pages such as

localhost:8080/api/add 
localhost:8080/api/subtract

I am new to Racket and have just used PHP in the past to handle GET parameter passing via the URL.

such as...

localhost:8080/api/add/?num1=1&num2=3

num1 would be accessed by PHP with

$_GET[ 'num1' ] ;

How should this be done in Racket? I have not found anything in the Racket documentation that shows an equivalent method. My final intent is to pass JSON strings as the GET parameter JSON

localhost:8080/api/add/?json={ some json }

Solution

  • Ok so I found the solution in

    POST/GET bindings in Racket

    essentially to get

    localhost:8080/api/add/?json={ some json }
    

    you would use

    (bytes->string/utf-8 
        (binding:form-value 
            (bindings-assq (string->bytes/utf-8 "[field_name_here]") 
                           (request-bindings/raw req))))
    

    Now this answers my question but lets me run into exceptions when the binding searched for is not present, so I decided to take it an extra step and perform an existence check. In PHP I want to perform something like...

    <?php 
    
        function get_param_as_string( $param ) {
            if ( isset( $_GET[ $param ] ) )
                return $_GET[ $param ] ;
            return "" ;
        }
    
    ?>
    

    So I created the racket procedure

    (define (get-param->string req param)
        (if (eq? #f (bindings-assq (string->bytes/utf-8 param)
                                   (request-bindings/raw req)))
            ""
            (bytes->string/utf-8 
               (binding:form-value 
                   (bindings-assq (string->bytes/utf-8 param)
                                  (request-bindings/raw req))))))
    

    Now as in the case specified by the question of the url

    localhost:8080/api/add/?json={ some json }
    

    The following would retrieve the json GET variable if present or would return "" if missing. so...

    (get-param->string req "json")
    

    would result in...

    { some json }
    

    and

    localhost:8080/api/add/?tmp={ some json }
    

    or

    localhost:8080/api/add/
    

    would result in...

    ""