Advertisement
metalx1000

Basic Webserver 1

Jun 13th, 2014
434
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. This creates a web server on port 8080
  3. It servers up output from this script.
  4. example: http://localhost:8080/hello
  5.  
  6. This does not server files or directories
  7. #>
  8. $routes = @{
  9.     "/hello" = { return '<html><body>Hello world!</body></html>' }
  10. }
  11.  
  12. $url = 'http://localhost:8080/'
  13. $listener = New-Object System.Net.HttpListener
  14. $listener.Prefixes.Add($url)
  15. $listener.Start()
  16.  
  17. Write-Host "Listening at $url..."
  18.  
  19. while ($listener.IsListening)
  20. {
  21.     $context = $listener.GetContext()
  22.     $requestUrl = $context.Request.Url
  23.     $response = $context.Response
  24.  
  25.     Write-Host ''
  26.     Write-Host "> $requestUrl"
  27.  
  28.     $localPath = $requestUrl.LocalPath
  29.     $route = $routes.Get_Item($requestUrl.LocalPath)
  30.  
  31.     if ($route -eq $null)
  32.     {
  33.         $response.StatusCode = 404
  34.     }
  35.     else
  36.     {
  37.         $content = & $route
  38.         $buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
  39.         $response.ContentLength64 = $buffer.Length
  40.         $response.OutputStream.Write($buffer, 0, $buffer.Length)
  41.     }
  42.    
  43.     $response.Close()
  44.  
  45.     $responseStatus = $response.StatusCode
  46.     Write-Host "< $responseStatus"
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement