Chi Template
This template deploys a base ready-to-use Chi app.
-
Two examples of custom middleware:
-
TrustProxy: Checks if the request IP matches one of the provided ranges/IPs, then inspects common reverse proxy headers and sets the corresponding, fields in the HTTP request struct for use by middleware or handlers that are next.
Useful for trusting the
X-Forwarded-For
andX-Forwarded-Proto
headers that Railway's proxy sets. -
Logger: The Logger middleware gathers metrics from the upstream handlers (status code, duration, bytes written) and logs them to stdout.
-
-
Comes with some helpful internal packages:
-
logger: The internal logger package is centered around Go's slog package but has some pre-configured loggers for added ease of use.
-
router: This is where the Chi router is initialized and global middlewares are registered like the
TrustProxy
andLogger
middlewares. Along with registering some handlers and path prefixes. -
responder: Comes with a few utility functions to send json (formatted and unformatted) or plaintext responses to the http client.
-
tools: Simple tools package, currently only has a
EnvPortOr
function that reads thePORT
variable from the environment or falls back to the provided port. -
server: This is where the
http.Server
settings are configured and the server is started from. -
routes: Where all the handlers and paths live, this template comes with the following prefixes and handlers:
/
: Returns a greeting message./health
: Returns just a 200 status code./api/
: The api prefix, with a subrouter./api/v1/
: The v1 prefix with a subrouter, registered on the/api/
subrouter./api/v1/temperature
: Simple mock api endpoint./api/v1/forecast/3day
: Just another mock api endpoint, but with a path parameter.
-
-
Download the Go modules:
go mod download
-
Start the server:
go run main.go
-
Open the browser or any api test program to
http://127.0.0.1:3000
-
Start coding!
- The http server listens on port
3000
if no environment variablePORT
is found, and once on Railway aPORT
variable is automatically generated, andEnvPortOr
will use thatPORT
instead of3000
.