83 lines
1.5 KiB
Go
Raw Normal View History

2024-03-22 14:08:24 +00:00
package web
2024-03-16 14:22:47 +00:00
2024-03-27 23:30:49 +00:00
import (
"bufio"
"git.akyoto.dev/go/router"
)
2024-03-16 14:22:47 +00:00
// Request is an interface for HTTP requests.
type Request interface {
2024-03-27 21:12:16 +00:00
Header(string) string
2024-03-27 13:06:13 +00:00
Host() string
2024-03-16 14:22:47 +00:00
Method() string
Path() string
2024-03-27 13:06:13 +00:00
Scheme() string
2024-03-27 19:41:27 +00:00
Param(string) string
2024-03-16 14:22:47 +00:00
}
// request represents the HTTP request used in the given context.
type request struct {
2024-03-27 23:30:49 +00:00
reader *bufio.Reader
2024-03-27 21:12:16 +00:00
scheme string
host string
method string
path string
query string
2024-03-28 11:22:45 +00:00
headers []Header
2024-03-27 21:12:16 +00:00
body []byte
params []router.Parameter
}
// Header returns the header value for the given key.
func (req *request) Header(key string) string {
for _, header := range req.headers {
if header.Key == key {
return header.Value
}
}
return ""
2024-03-16 14:22:47 +00:00
}
2024-03-27 13:06:13 +00:00
// Host returns the requested host.
func (req *request) Host() string {
return req.host
}
2024-03-16 14:22:47 +00:00
// Method returns the request method.
2024-03-26 21:46:16 +00:00
func (req *request) Method() string {
return req.method
2024-03-16 14:22:47 +00:00
}
2024-03-27 19:41:27 +00:00
// Param retrieves a parameter.
func (req *request) Param(name string) string {
for i := range len(req.params) {
p := req.params[i]
if p.Key == name {
return p.Value
}
}
return ""
}
2024-03-16 14:22:47 +00:00
// Path returns the requested path.
2024-03-26 21:46:16 +00:00
func (req *request) Path() string {
return req.path
2024-03-16 14:22:47 +00:00
}
2024-03-27 13:06:13 +00:00
// Scheme returns either `http`, `https` or an empty string.
func (req request) Scheme() string {
return req.scheme
}
2024-03-26 21:46:16 +00:00
// addParameter adds a new parameter to the request.
func (req *request) addParameter(key string, value string) {
req.params = append(req.params, router.Parameter{
Key: key,
Value: value,
})
2024-03-16 14:22:47 +00:00
}