80 lines
1.7 KiB
Go
Raw Normal View History

2024-03-22 14:08:24 +00:00
package web
2024-03-16 14:22:47 +00:00
import (
"io"
)
// Response is the interface for an HTTP response.
type Response interface {
2024-03-26 21:46:16 +00:00
io.Writer
io.StringWriter
Body() []byte
2024-03-27 19:41:27 +00:00
Header(string) string
2024-03-16 14:22:47 +00:00
SetHeader(key string, value string)
2024-03-26 21:46:16 +00:00
SetBody([]byte)
2024-03-27 19:41:27 +00:00
SetStatus(int)
2024-03-26 21:46:16 +00:00
Status() int
2024-03-16 14:22:47 +00:00
}
// response represents the HTTP response used in the given context.
type response struct {
2024-03-26 21:46:16 +00:00
body []byte
2024-03-28 11:22:45 +00:00
headers []Header
2024-03-26 21:46:16 +00:00
status uint16
2024-03-16 14:22:47 +00:00
}
2024-03-26 21:46:16 +00:00
// Body returns the response body.
func (res *response) Body() []byte {
return res.body
2024-03-22 13:37:21 +00:00
}
2024-03-16 14:22:47 +00:00
// Header returns the header value for the given key.
2024-03-26 21:46:16 +00:00
func (res *response) Header(key string) string {
for _, header := range res.headers {
if header.Key == key {
return header.Value
}
}
return ""
2024-03-16 14:22:47 +00:00
}
// SetHeader sets the header value for the given key.
2024-03-26 21:46:16 +00:00
func (res *response) SetHeader(key string, value string) {
2024-03-27 19:41:27 +00:00
for i, header := range res.headers {
2024-03-26 21:46:16 +00:00
if header.Key == key {
2024-03-27 19:41:27 +00:00
res.headers[i].Value = value
2024-03-26 21:46:16 +00:00
return
}
}
2024-03-28 11:22:45 +00:00
res.headers = append(res.headers, Header{Key: key, Value: value})
2024-03-26 21:46:16 +00:00
}
// 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)
2024-03-16 14:22:47 +00:00
}
// Write implements the io.Writer interface.
2024-03-26 21:46:16 +00:00
func (res *response) Write(body []byte) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
2024-03-16 14:22:47 +00:00
}
// WriteString implements the io.StringWriter interface.
2024-03-26 21:46:16 +00:00
func (res *response) WriteString(body string) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
}