CS3700-project4/smol-http/main.rkt

53 lines
1.3 KiB
Racket
Raw Normal View History

#lang racket/base
(provide (all-from-out "./http-msg.rkt")
http-request-method?
http-response-code?
2020-04-11 03:10:28 +00:00
http-response-code-name
http-socket?
http-connect
http-request
http-close)
2020-04-11 03:10:28 +00:00
(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?
2020-04-11 03:33:45 +00:00
(define (http-connect host
[port DEFAULT-PORT]
2020-04-11 03:10:28 +00:00
#:headers [x-hdrs '()])
2020-04-11 03:33:45 +00:00
(http-socket `([host . ,host] ,@x-hdrs)
2020-04-11 03:10:28 +00:00
(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))
2020-04-11 03:34:42 +00:00
;; (http-request sock req) -> http-res?
2020-04-11 03:10:28 +00:00
;; sock : http-socket?
;; req : http-req?
(define (http-request sock req)
2020-04-11 03:33:45 +00:00
(define req* (http-add-headers req (http-socket-extra-headers sock)))
2020-04-11 03:10:28 +00:00
(match-define (cons in out) (http-socket-conn-pair sock))
(write-http-msg req* out)
(flush-output out)
(read-http-msg in))
2020-04-11 03:10:28 +00:00
(module+ test
)