Basic Server
Minimal server: one HTTP listener (loopback:5000) + a single PowerShell route returning text.
Prerequisites: see Introduction.
Full source
File: pwsh/tutorial/examples/7.1-Basic-Server.ps1
<#
Sample Kestrun Server - Basic Server
This script demonstrates the minimal steps to run a Kestrun server
with a single HTTP listener and one PowerShell route.
FileName: 7.1-Basic-Server.ps1
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback
)
# (Optional) Configure console logging so we can see events
New-KrLogger | Set-KrLoggerLevel -Value Debug |
Add-KrSinkConsole |
Register-KrLogger -Name 'console' -SetAsDefault | Out-Null
# Create a new Kestrun server
New-KrServer -Name 'Endpoints Basic'
# Add a listener on the configured port and IP address
Add-KrEndpoint -Port $Port -IPAddress $IPAddress
# Enable Kestrun configuration
Enable-KrConfiguration
# Map the route
Add-KrMapRoute -Verbs Get -Pattern '/hello' -ScriptBlock {
Write-KrLog -Level Information -Message 'Processing /hello request'
Write-KrTextResponse -InputObject 'Hello from basic server' -StatusCode 200
}
# Initial informational log
Write-KrLog -Level Information -Message 'Server {Name} configured.' -Values 'Endpoints Basic'
# Start the server and close all the loggers when the server stops
# This is equivalent to calling Close-KrLogger after Start-KrServer
Start-KrServer -CloseLogsOnExit
Step-by-step
- Server:
New-KrServercreates a named instance. - Listener:
Add-KrEndpoint -Port 5000 -IPAddress Loopbackbinds HTTP. - Commit:
Enable-KrConfigurationapplies staged configuration. - Route:
Add-KrMapRouteregisters/hellousingWrite-KrTextResponse. - Start:
Start-KrServerbegins processing (Ctrl+C to stop). - Logging (optional): console logger shows
Write-KrLogevents.
Try it
curl http://127.0.0.1:5000/hello
Invoke-WebRequest -Uri http://127.0.0.1:5000/hello | Select-Object -ExpandProperty Content
Expected: Hello from basic server.
References
- New-KrServer
- Add-KrEndpoint
- Enable-KrConfiguration
- Add-KrMapRoute
- Write-KrTextResponse
- Start-KrServer
- Write-KrLog
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| 404 Not Found | Wrong route pattern | Ensure pattern starts with / and matches request |
| Port in use | Another process bound to 5000 | Use a different port (-Port 5001) |
| No logs shown | Logger not default | Add logger and -SetAsDefault |
See also: Routes · Simple Logging
Previous / Next
Go back to Tutorial Index or continue to Multiple Listeners.