Web/response.go
2024-09-05 22:02:43 -05:00

78 lines
1.6 KiB
Go

package web
import "io"
// Interface for an HTTP response.
type Response interface {
io.Writer
io.StringWriter
Body() []byte
Header(string) string
SetHeader(key string, value string)
SetBody([]byte)
SetStatus(int)
Status() int
}
// Represents the HTTP response used in the given context.
type response struct {
body []byte
headers []Header
status uint16
}
// Returns the response body.
func (res *response) Body() []byte {
return res.body
}
// Returns the header value for the given key.
func (res *response) Header(key string) string {
for _, header := range res.headers {
if header.Key == key {
return header.Value
}
}
return ""
}
// Sets the header value for the given key.
func (res *response) SetHeader(key string, value string) {
for i, header := range res.headers {
if header.Key == key {
res.headers[i].Value = value
return
}
}
res.headers = append(res.headers, Header{Key: key, Value: value})
}
// Replaces the response body with the new contents.
func (res *response) SetBody(body []byte) {
res.body = body
}
// Sets the HTTP status code.
func (res *response) SetStatus(status int) {
res.status = uint16(status)
}
// Returns the HTTP status code.
func (res *response) Status() int {
return int(res.status)
}
// Implements the io.Writer interface for the body.
func (res *response) Write(body []byte) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
}
// Implements the io.StringWriter interface for the body.
func (res *response) WriteString(body string) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
}