Removed net/http

This commit is contained in:
2024-03-26 22:46:16 +01:00
parent f4617248d8
commit 271e1cd5bd
11 changed files with 230 additions and 629 deletions

View File

@ -2,48 +2,95 @@ package web
import (
"io"
"net/http"
"strings"
"git.akyoto.dev/go/router"
)
// Response is the interface for an HTTP response.
type Response interface {
Flush()
io.Writer
io.StringWriter
Body() []byte
Header(key string) string
SetHeader(key string, value string)
Write([]byte) (int, error)
WriteString(string) (int, error)
SetBody([]byte)
SetStatus(status int)
Status() int
}
// response represents the HTTP response used in the given context.
type response struct {
http.ResponseWriter
body []byte
status uint16
headers []router.Parameter
}
// Flush flushes the response buffers to the client.
func (res response) Flush() {
flusher, ok := res.ResponseWriter.(http.Flusher)
if ok {
flusher.Flush()
}
// Body returns the response body.
func (res *response) Body() []byte {
return res.body
}
// Header returns the header value for the given key.
func (res response) Header(key string) string {
return res.ResponseWriter.Header().Get(key)
func (res *response) Header(key string) string {
for _, header := range res.headers {
if header.Key == key {
return header.Value
}
}
return ""
}
// SetHeader sets the header value for the given key.
func (res response) SetHeader(key string, value string) {
res.ResponseWriter.Header().Set(key, value)
func (res *response) SetHeader(key string, value string) {
for _, header := range res.headers {
if header.Key == key {
header.Value = value
return
}
}
res.headers = append(res.headers, router.Parameter{Key: key, Value: value})
}
// SetBody replaces the response body with the new contents.
func (res *response) SetBody(body []byte) {
res.body = body
}
// SetStatus sets the HTTP status code.
func (res *response) SetStatus(status int) {
res.status = uint16(status)
}
// Status returns the HTTP status code.
func (res *response) Status() int {
return int(res.status)
}
// Write implements the io.Writer interface.
func (res response) Write(body []byte) (int, error) {
return res.ResponseWriter.Write(body)
func (res *response) Write(body []byte) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
}
// WriteString implements the io.StringWriter interface.
func (res response) WriteString(body string) (int, error) {
return res.ResponseWriter.(io.StringWriter).WriteString(body)
func (res *response) WriteString(body string) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
}
// headerText combines all HTTP headers into a single string.
func (res *response) headerText() string {
combined := strings.Builder{}
for _, header := range res.headers {
combined.WriteString(header.Key)
combined.WriteString(": ")
combined.WriteString(header.Value)
combined.WriteString("\r\n")
}
return combined.String()
}