-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.ps1
60 lines (49 loc) · 1.98 KB
/
server.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
Add-Type -AssemblyName System.Web
Class FunctionContext{
[string] $Method;
[string] $Request;
[string] $Body;
[System.Net.WebHeaderCollection] $Headers;
[System.Collections.Specialized.NameValueCollection] $Query;
[string] $Path;
}
Class FunctionResponse{
[string] $Body;
[System.Net.WebHeaderCollection] $Headers;
[int] $Status;
}
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add("http://*:8082/")
$listener.Start()
. "./function/handler.ps1"
do {
$context = $listener.GetContext()
$response = $context.Response
$Content = ""
$reqStream = $context.Request.InputStream
$reqEncoding = $context.Request.ContentEncoding
$reader = [System.IO.StreamReader]::new($reqStream, $reqEncoding)
$fnContext = [FunctionContext]::new()
$fnContext.Body = $reader.ReadToEnd()
$fnContext.Headers = $context.Request.Headers
$fnContext.Method = $context.Request.HttpMethod
$fnContext.Query = $context.Request.QueryString
$fnContext.Path = $context.Request.Url.LocalPath
$fnContext.Request = $context.Request
$fnResponse = [FunctionResponse]::new()
$fnResponse.Headers = [System.Net.WebHeaderCollection]::new()
try {
Handler -fnContext $fnContext -fnResponse $fnResponse
$Content = [System.Text.Encoding]::UTF8.GetBytes($fnResponse.Body)
$response.StatusCode = $(If ($fnResponse.Status) {$fnResponse.Status} Else {200}) #default to 200 response if not set
}
catch {
$responseBody = $(If ($_.Exception.Message) {$_.Exception.Message} Else {$fnResponse.Body})
$Content = [System.Text.Encoding]::UTF8.GetBytes($responseBody)
$response.StatusCode = $(If ($fnResponse.Status) {$fnResponse.Status} Else {500}) #default to 500 response for exceptions
}
$response.Headers = $fnResponse.Headers
$response.ContentLength64 = $Content.Length
$response.OutputStream.Write($Content, 0, $Content.Length)
$response.Close()
} while ($listener.IsListening)