11import * as http from 'http' ;
2+ import * as http2 from 'http2' ;
23
34import { clearArray } from './util.js' ;
45
56import { httpEndpoints } from './endpoints/endpoint-index.js' ;
7+ import { HttpRequest , HttpResponse } from './endpoints/http-index.js' ;
68
7- const allowCORS = ( req : http . IncomingMessage , res : http . ServerResponse ) => {
9+ const allowCORS = ( req : HttpRequest , res : HttpResponse ) => {
810 const origin = req . headers [ 'origin' ] ;
911 if ( ! origin ) return ;
1012
@@ -24,10 +26,15 @@ const allowCORS = (req: http.IncomingMessage, res: http.ServerResponse) => {
2426 }
2527}
2628
27- export function createHttpHandler ( options : {
29+ type RequestHandler = (
30+ req : HttpRequest ,
31+ res : HttpResponse
32+ ) => Promise < void > ;
33+
34+ function createHttpRequestHandler ( options : {
2835 acmeChallengeCallback : ( token : string ) => string | undefined
29- } ) {
30- async function handleRequest ( req : http . IncomingMessage , res : http . ServerResponse ) {
36+ } ) : RequestHandler {
37+ return async function handleRequest ( req , res ) {
3138 const url = new URL ( req . url ! , `http://${ req . headers . host } ` ) ;
3239 const path = url . pathname ;
3340
@@ -84,10 +91,44 @@ export function createHttpHandler(options: {
8491 res . end ( `No handler for ${ req . url } ` ) ;
8592 }
8693 }
94+ }
8795
96+ export function createHttp1Handler ( options : {
97+ acmeChallengeCallback : ( token : string ) => string | undefined
98+ } ) {
99+ const handleRequest = createHttpRequestHandler ( options ) ;
88100 const handler = new http . Server ( async ( req , res ) => {
89101 try {
90- console . log ( `Handling request to ${ req . url } ` ) ;
102+ console . log ( `Handling H1 request to ${ req . url } ` ) ;
103+ await handleRequest ( req , res ) ;
104+ } catch ( e ) {
105+ console . error ( e ) ;
106+
107+ if ( res . closed ) return ;
108+ else if ( res . headersSent ) {
109+ res . destroy ( ) ;
110+ } else {
111+ res . writeHead ( 500 ) ;
112+ res . end ( 'HTTP handler failed' ) ;
113+ }
114+ } finally {
115+ // We have to clear this, as we might get multiple requests on the same
116+ // socket with keep-alive etc.
117+ clearArray ( req . socket . receivedData ) ;
118+ }
119+ } ) ;
120+
121+ handler . on ( 'error' , ( err ) => console . error ( 'HTTP handler error' , err ) ) ;
122+
123+ return handler ;
124+ }
125+
126+ export function createHttp2Handler ( options : {
127+ acmeChallengeCallback : ( token : string ) => string | undefined
128+ } ) {
129+ const handleRequest = createHttpRequestHandler ( options ) ;
130+ const handler = http2 . createServer ( async ( req , res ) => {
131+ try {
91132 await handleRequest ( req , res ) ;
92133 } catch ( e ) {
93134 console . error ( e ) ;
0 commit comments