gradio

Форк
0
/
http.ts 
77 строк · 1.9 Кб
1
export interface HttpRequest {
2
	method: "GET" | "POST" | "PUT" | "DELETE";
3
	path: string;
4
	query_string: string; // This field must not contain the leading `?`, as it's directly used in the ASGI spec which requires this.
5
	headers: Record<string, string>;
6
	body?: Uint8Array | ReadableStream<Uint8Array> | null;
7
}
8
export interface HttpResponse {
9
	status: number;
10
	headers: Record<string, string>;
11
	body: Uint8Array;
12
}
13

14
// Inspired by https://github.com/rstudio/shinylive/blob/v0.1.2/src/messageporthttp.ts
15
export function headersToASGI(
16
	headers: HttpRequest["headers"]
17
): [string, string][] {
18
	const result: [string, string][] = [];
19
	for (const [key, value] of Object.entries(headers)) {
20
		result.push([key, value]);
21
	}
22
	return result;
23
}
24

25
export function uint8ArrayToString(buf: Uint8Array): string {
26
	let result = "";
27
	for (let i = 0; i < buf.length; i++) {
28
		result += String.fromCharCode(buf[i]);
29
	}
30
	return result;
31
}
32

33
export function asgiHeadersToRecord(headers: any): Record<string, string> {
34
	headers = headers.map(([key, val]: [Uint8Array, Uint8Array]) => {
35
		return [uint8ArrayToString(key), uint8ArrayToString(val)];
36
	});
37
	return Object.fromEntries(headers);
38
}
39

40
export function getHeaderValue(
41
	headers: HttpRequest["headers"],
42
	key: string
43
): string | undefined {
44
	// The keys in `headers` are case-insensitive.
45
	const unifiedKey = key.toLowerCase();
46
	for (const [k, v] of Object.entries(headers)) {
47
		if (k.toLowerCase() === unifiedKey) {
48
			return v;
49
		}
50
	}
51
}
52

53
export function logHttpReqRes(
54
	request: HttpRequest,
55
	response: HttpResponse
56
): void {
57
	if (Math.floor(response.status / 100) !== 2) {
58
		let bodyText: string;
59
		let bodyJson: unknown;
60
		try {
61
			bodyText = new TextDecoder().decode(response.body);
62
		} catch (e) {
63
			bodyText = "(failed to decode body)";
64
		}
65
		try {
66
			bodyJson = JSON.parse(bodyText);
67
		} catch (e) {
68
			bodyJson = "(failed to parse body as JSON)";
69
		}
70
		console.error("Wasm HTTP error", {
71
			request,
72
			response,
73
			bodyText,
74
			bodyJson
75
		});
76
	}
77
}
78

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.