-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebserver.ps1
60 lines (50 loc) · 1.52 KB
/
webserver.ps1
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
59
60
[string] $listenUrl = 'http://*:80/'
function ProcessData($data)
{
$json = $data | ConvertFrom-Json
}
$htmlcontents = @{
'GET /' = '<html>Hi</html>'
'POST /' = "success"
}
# start web server
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($listenUrl)
$listener.Start()
try
{
while ($listener.IsListening)
{
# process received request
$context = $listener.GetContext()
$Request = $context.Request
$Response = $context.Response
$received = '{0} {1}' -f $Request.httpmethod, $Request.url.localpath
write-host "Recieved request $received"
# is there HTML content for this URL?
$html = $htmlcontents[$received]
if ($html -eq $null)
{
$Response.statuscode = 404
$html = 'Oops, the page is not available!'
}
if ($REQUEST.HasEntityBody)
{
$reader = New-Object System.IO.StreamReader($Request.InputStream, $request.ContentEncoding)
$data = $reader.ReadToEnd()
$reader.Close()
$request.InputStream.Close()
ProcessData $data
write-host $data
}
# return the HTML to the caller
$buffer = [Text.Encoding]::UTF8.GetBytes($html)
$Response.ContentLength64 = $buffer.length
$Response.OutputStream.Write($buffer, 0, $buffer.length)
$Response.Close()
}
}
finally
{
$listener.Stop()
}