-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpListener.ps1
More file actions
58 lines (52 loc) · 1.81 KB
/
HttpListener.ps1
File metadata and controls
58 lines (52 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# HttpListener.ps1
# Simple HTTP listener to verify Wirespeed-Forwarder.ps1 message forwarding with pretty-printed JSON
param (
[string]$Url = "http://localhost", # Base URL for the listener (default: http://localhost)
[int]$Port = 8080 # Port to listen on (default: 8080)
)
# Construct the full listener prefix
$listenerPrefix = "$Url`:$Port/"
$listener = [System.Net.HttpListener]::new()
try {
# Set up the listener
$listener.Prefixes.Add($listenerPrefix)
$listener.Start()
Write-Host "Listening on $listenerPrefix..."
# Main loop to handle incoming requests
while ($true) {
$context = $listener.GetContext()
if ($context.Request.HttpMethod -eq "POST") {
# Read the entire request body
$reader = [System.IO.StreamReader]::new($context.Request.InputStream)
$body = $reader.ReadToEnd()
$reader.Close()
# Pretty-print the JSON body
try {
$jsonObject = $body | ConvertFrom-Json
$prettyJson = $jsonObject | ConvertTo-Json -Depth 10
Write-Host "Received POST body:"
Write-Host $prettyJson
}
catch {
Write-Host "Received POST body (raw, non-JSON): $body"
}
# Send a 200 OK response
$response = $context.Response
$response.StatusCode = 200
$writer = [System.IO.StreamWriter]::new($response.OutputStream)
$writer.Write("OK")
$writer.Close()
$response.Close()
}
}
}
catch {
Write-Host "Error: $($_.Exception.Message)"
}
finally {
# Ensure the listener is stopped if an error occurs or script is interrupted
if ($listener.IsListening) {
$listener.Stop()
}
$listener.Close()
}