| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Writes plain text to the HTTP response body. |
| | | 4 | | |
| | | 5 | | .DESCRIPTION |
| | | 6 | | Sends a raw text payload to the client and optionally sets the HTTP status |
| | | 7 | | code and content type. |
| | | 8 | | |
| | | 9 | | .PARAMETER InputObject |
| | | 10 | | The text content to write to the response body. This can be a string or any |
| | | 11 | | other object that can be converted to a string. |
| | | 12 | | |
| | | 13 | | .PARAMETER StatusCode |
| | | 14 | | The HTTP status code to set for the response. Defaults to 200 (OK). |
| | | 15 | | |
| | | 16 | | .PARAMETER ContentType |
| | | 17 | | The content type of the response. If not specified, defaults to "text/plain". |
| | | 18 | | |
| | | 19 | | .EXAMPLE |
| | | 20 | | Write-KrTextResponse -InputObject "Hello, World!" -StatusCode 200 |
| | | 21 | | Writes "Hello, World!" to the response body with a 200 OK status code. |
| | | 22 | | |
| | | 23 | | .NOTES |
| | | 24 | | This function is designed to be used in the context of a Kestrun server response. |
| | | 25 | | #> |
| | | 26 | | function Write-KrTextResponse { |
| | | 27 | | [KestrunRuntimeApi('Route')] |
| | | 28 | | [CmdletBinding()] |
| | | 29 | | param( |
| | | 30 | | [Parameter(Mandatory = $true, ValueFromPipeline = $true)] |
| | | 31 | | [Alias('Text')] |
| | | 32 | | [object]$InputObject, |
| | | 33 | | [Parameter()] |
| | | 34 | | [int]$StatusCode = 200, |
| | | 35 | | [Parameter()] |
| | | 36 | | [string]$ContentType |
| | | 37 | | ) |
| | | 38 | | begin { |
| | | 39 | | # Collect all piped items |
| | 0 | 40 | | $items = [System.Collections.Generic.List[object]]::new() |
| | | 41 | | } |
| | | 42 | | process { |
| | | 43 | | # Accumulate; no output yet |
| | 0 | 44 | | $items.Add($InputObject) |
| | | 45 | | } |
| | | 46 | | end { |
| | | 47 | | # Only works inside a route script block where $Context is available |
| | 0 | 48 | | if ($null -eq $Context -or $null -eq $Context.Response) { |
| | 0 | 49 | | Write-KrOutsideRouteWarning |
| | | 50 | | return |
| | | 51 | | } |
| | | 52 | | # - single item by default when only one was piped |
| | | 53 | | # - array if multiple items were piped |
| | 0 | 54 | | $payload = if ($items.Count -eq 1) { $items[0] } else { $items.ToArray() } |
| | | 55 | | |
| | | 56 | | # Write the CBOR response |
| | 0 | 57 | | $Context.Response.WriteTextResponse($payload, $StatusCode, $ContentType) |
| | | 58 | | } |
| | | 59 | | } |
| | | 60 | | |