文件
一個 專案

respond

向客戶端寫入硬編碼/靜態回應。

如果 body 非空,此指令會設定 Content-Type 標頭(如果尚未設定)。預設值為 text/plain; utf-8,除非 body 是有效的 JSON 物件或陣列,在這種情況下,它會設定為 application/json。對於所有其他內容類型,請使用 header 指令 明確設定正確的 Content-Type。

語法

respond [<matcher>] <status>|<body> [<status>] {
	body <text>
	close
}
  • <status> 是要寫入的 HTTP 狀態碼。

    如果為 103 (Early Hints),回應將在沒有 body 的情況下寫入,並且處理程序鏈將繼續。(HTTP 1xx 回應是資訊性的,不是最終回應。)

    預設值:200

  • <body> 是要寫入的回應 body。

  • body 是提供 body 的另一種方式;如果 body 是多行,則很方便。

  • close 將在寫入回應後關閉客戶端與伺服器的連線。

為了清楚起見,第一個非比對器參數可以是 3 位數的狀態碼或回應 body 字串。如果它是 body,則下一個參數可以是狀態碼。

範例

對所有健康檢查寫入空的 200 狀態和空的 body,並對所有其他請求寫入簡單的回應 body

example.com {
	respond /health-check 200
	respond "Hello, world!"
}

寫入錯誤回應並關閉連線

example.com {
	respond /secret/* "Access denied" 403 {
		close
	}
}

寫入 HTML 回應,使用 heredoc 語法 來控制空格,並設定 Content-Type 標頭以符合回應 body

example.com {
	header Content-Type text/html
	respond <<HTML
		<html>
			<head><title>Foo</title></head>
			<body>Foo</body>
		</html>
		HTML 200
}