#lang racket/base (provide (all-from-out "./http-msg.rkt") http-request-method? http-response-code? http-response-code-name http-socket? http-connect http-request http-close) (require racket/tcp racket/match "./util.rkt" "./http-msg.rkt") ;; --------------------------------------------------------------------------------------- (define DEFAULT-PORT 80) (struct http-socket [extra-headers conn-pair]) ;; (http-connect host [port]) -> http-socket? ;; host : string? ;; port : port-number? (define (http-connect host [port DEFAULT-PORT] #:headers [x-hdrs '()]) (http-socket `([host . ,host] ,@x-hdrs) (let-values ([(in out) (tcp-connect host port)]) (cons in out)))) ;; (http-close sock) -> void? ;; sock : http-socket? (define (http-close sock) (match-define (cons in out) (http-socket-conn-pair sock)) (tcp-abandon-port in) (tcp-abandon-port out)) ;; (http-request sock req) -> http-res? ;; sock : http-socket? ;; req : http-req? (define (http-request sock req) (define req* (http-add-headers req (http-socket-extra-headers sock))) (match-define (cons in out) (http-socket-conn-pair sock)) (write-http-msg req* out) (flush-output out) (read-http-msg in)) (module+ test )