🌐 Web server.
|
||
---|---|---|
examples | ||
send | ||
.gitignore | ||
Context.go | ||
Context_test.go | ||
go.mod | ||
go.sum | ||
Handler.go | ||
Header.go | ||
http.go | ||
Query.go | ||
Query_test.go | ||
readme.md | ||
Request.go | ||
Request_test.go | ||
Response.go | ||
Response_test.go | ||
Server.go | ||
Server_test.go |
web
A minimal HTTP/1.1 web server that sits behind a reverse proxy like caddy
, haproxy
or nginx
for HTTP 1/2/3 support.
Features
- Low latency
- High throughput
- Scales incredibly well
Installation
go get git.urbach.dev/go/web
Usage
Quick start
s := web.NewServer()
// add routes here
s.Run(":8080")
Static route
s.Get("/", func(ctx web.Context) error {
return ctx.String("Hello")
})
Parameter route
s.Get("/blog/:post", func(ctx web.Context) error {
post := ctx.Request().Param("post")
return ctx.String(post)
})
Wildcard route
s.Get("/images/*file", func(ctx web.Context) error {
file := ctx.Request().Param("file")
return ctx.String(file)
})
REST methods
s.Post("/api/user/:id", func(ctx web.Context) error {
id := ctx.Request().Param("id")
return ctx.String(id)
})
Middleware
Registration
// Single function
s.Use(middleware)
// Multiple functions
s.Use(middleware1, middleware2, middleware3)
Example: Response time logging
func ResponseTime(ctx web.Context) error {
start := time.Now()
defer func() {
fmt.Println(ctx.Request().Path(), time.Since(start))
}()
return ctx.Next(ctx)
}
Example: Recover from panics
func Recover(ctx web.Context) error {
defer func() {
err := recover()
if err != nil {
fmt.Println(err)
}
}()
return ctx.Next(ctx)
}
Example: Custom contexts
type Custom struct {
web.Context
User string
}
s.Use(func(ctx web.Context) error {
custom := &Custom{Context: ctx, User: "admin"}
return ctx.Next(custom)
})
s.Get("/", func(ctx web.Context) error {
custom := ctx.(*Custom)
return ctx.String(ctx.User)
})
Query parameters
s.Get("/search", func(ctx web.Context) error {
term := ctx.Query().Param("term")
return ctx.String(term)
})
Custom 404 page
s.All("/*", func(ctx web.Context) error {
return ctx.Status(404).String("Not found")
})
Tests
PASS: TestBytes
PASS: TestString
PASS: TestError
PASS: TestErrorMultiple
PASS: TestRedirect
PASS: TestQueryParam
PASS: TestQueryParamDuplicate
PASS: TestQueryParamEmpty
PASS: TestQueryParamWithSpace
PASS: TestRequest
PASS: TestRequestBody
PASS: TestRequestBodyMissingLength
PASS: TestRequestHeader
PASS: TestRequestMethods
PASS: TestRequestMethodsAll
PASS: TestRequestParam
PASS: TestWrite
PASS: TestWriteString
PASS: TestResponseCompression
PASS: TestResponseHeader
PASS: TestResponseHeaderOverwrite
PASS: TestPanic
PASS: TestRun
PASS: TestBadRequest
PASS: TestBadRequestHeader
PASS: TestBadRequestMethod
PASS: TestBadRequestPath
PASS: TestBadRequestProtocol
PASS: TestConnectionClose
PASS: TestEarlyClose
PASS: TestSetErrorHandler
PASS: TestUnavailablePort
coverage: 100.0% of statements
Benchmarks
Contributors
License
Please see the license documentation.
Copyright
© 2024 Eduard Urbach