UNPKG

kaven-utils

Version:

Utils for Node.js.

103 lines (102 loc) 3.42 kB
/******************************************************************** * @author: Kaven * @email: kaven@wuwenkai.com * @website: http://blog.kaven.xyz * @file: [Kaven-Utils] /src/net/http/HttpRequestMessage.ts * @create: 2022-04-14 18:03:59.916 * @modify: 2025-10-14 22:58:04.859 * @version: 6.1.0 * @times: 31 * @lines: 141 * @copyright: Copyright © 2022-2025 Kaven. All Rights Reserved. * @description: [description] * @license: [license] ********************************************************************/ import { HttpStandardRequestHeader_ContentLength, HttpStandardRequestHeader_Host, KavenUrl, Strings_CR_LF, } from "kaven-basic"; import { HttpRequestStartLine } from "./HttpRequestStartLine.js"; // https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages#:%7E:text=absolute%20form export class HttpRequestMessage { Index; StartLine = new HttpRequestStartLine(); Headers = []; Body; IsStartLineParsed = false; IsHeadersParsed = false; Logger; constructor(index = 0) { this.Index = index; } get ShouldParseBody() { if (!this.IsStartLineParsed) { return false; } if (!this.IsHeadersParsed) { return false; } if (this.BodySize === 0) { return false; } return true; } FindHeader(name) { return this.Headers.find(p => p.Name.toUpperCase() === name.toUpperCase()); } get BodySize() { const header = this.FindHeader(HttpStandardRequestHeader_ContentLength); if (header === undefined) { return 0; } return Number(header.Value); } get IsHttpRequest() { if (this.StartLine !== undefined && this.StartLine.IsHttpRequest) { return true; } return false; } get IsHttpConnect() { if (this.StartLine.IsHttpConnect) { return true; } return false; } get Address() { if (this.StartLine.IsHttpRequest && this.StartLine.RequestTarget !== undefined) { return this.StartLine.RequestTarget; } const host = this.FindHeader(HttpStandardRequestHeader_Host); if (host) { return new KavenUrl(host.Value); } throw new Error(); } get Port() { if (this.StartLine.RequestTarget?.Port !== undefined) { return this.StartLine.RequestTarget.Port; } const host = this.FindHeader(HttpStandardRequestHeader_Host); if (host) { const url = new KavenUrl(host.Value); if (url.Port !== undefined) { return url.Port; } } this.Logger?.Warn("The port could not be resolved, the default port will be used instead."); return this.IsHttpConnect ? 443 : 80; } GetAuthorizationInfo(headerName) { const header = this.FindHeader(headerName); return { authorization: header?.Value, method: this.StartLine.Method, }; } ToBuffer() { const lines = [this.StartLine.ToString(), ...this.Headers.map(p => p.ToString()), Strings_CR_LF]; const data = Buffer.from(lines.join(Strings_CR_LF)); if (this.Body === undefined) { return data; } return Buffer.concat([data, this.Body.Data]); } }