Added graceful shutdown

This commit is contained in:
2024-03-12 22:31:45 +01:00
parent b3c73282b3
commit 4b6cb6c34f
8 changed files with 116 additions and 31 deletions

View File

@ -21,8 +21,8 @@ type Context interface {
String(string) error
}
// context represents a request & response context.
type context struct {
// ctx represents a request & response context.
type ctx struct {
request request
response response
paramNames [maxParams]string
@ -31,8 +31,8 @@ type context struct {
}
// newContext returns a new context from the pool.
func newContext(req *http.Request, res http.ResponseWriter) *context {
ctx := contextPool.Get().(*context)
func newContext(req *http.Request, res http.ResponseWriter) *ctx {
ctx := contextPool.Get().(*ctx)
ctx.request.Request = req
ctx.response.ResponseWriter = res
ctx.paramCount = 0
@ -40,13 +40,13 @@ func newContext(req *http.Request, res http.ResponseWriter) *context {
}
// Bytes responds with a raw byte slice.
func (ctx *context) Bytes(body []byte) error {
func (ctx *ctx) Bytes(body []byte) error {
_, err := ctx.response.Write(body)
return err
}
// Error is used for sending error messages to the client.
func (ctx *context) Error(status int, messages ...any) error {
func (ctx *ctx) Error(status int, messages ...any) error {
var combined []error
for _, msg := range messages {
@ -63,7 +63,7 @@ func (ctx *context) Error(status int, messages ...any) error {
}
// Get retrieves a parameter.
func (ctx *context) Get(param string) string {
func (ctx *ctx) Get(param string) string {
for i := 0; i < ctx.paramCount; i++ {
if ctx.paramNames[i] == param {
return ctx.paramValues[i]
@ -74,29 +74,29 @@ func (ctx *context) Get(param string) string {
}
// Reader sends the contents of the io.Reader without creating an in-memory copy.
func (ctx *context) Reader(reader io.Reader) error {
func (ctx *ctx) Reader(reader io.Reader) error {
_, err := io.Copy(ctx.response, reader)
return err
}
// Request returns the HTTP request.
func (ctx *context) Request() Request {
func (ctx *ctx) Request() Request {
return &ctx.request
}
// Response returns the HTTP response.
func (ctx *context) Response() Response {
func (ctx *ctx) Response() Response {
return &ctx.response
}
// String responds with the given string.
func (ctx *context) String(body string) error {
func (ctx *ctx) String(body string) error {
slice := unsafe.Slice(unsafe.StringData(body), len(body))
return ctx.Bytes(slice)
}
// addParameter adds a new parameter to the context.
func (ctx *context) addParameter(name string, value string) {
func (ctx *ctx) addParameter(name string, value string) {
ctx.paramNames[ctx.paramCount] = name
ctx.paramValues[ctx.paramCount] = value
ctx.paramCount++