53 lines
1.4 KiB
Racket
53 lines
1.4 KiB
Racket
#lang racket/base
|
|
(provide (all-from-out "./http-msg.rkt")
|
|
http-request-method?
|
|
http-response-code?
|
|
http-response-code-name
|
|
|
|
http-socket?
|
|
http-connect)
|
|
|
|
(require racket/tcp
|
|
racket/match
|
|
|
|
"./util.rkt"
|
|
"./http-msg.rkt")
|
|
|
|
;; ---------------------------------------------------------------------------------------
|
|
|
|
(define DEFAULT-PORT 80)
|
|
(define DEFAULT-USER-AGENT "smol-http 0.0.1")
|
|
|
|
(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]
|
|
[user-agent . ,DEFAULT-USER-AGENT]
|
|
,@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 req [sock]) -> http-res?
|
|
;; sock : http-socket?
|
|
;; req : http-req?
|
|
(define (http-request sock req)
|
|
(define req* (http-set-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
|
|
)
|