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

89 lines
1.5 KiB
Go

package web
import (
"bufio"
router "git.sharkk.net/Go/Router"
)
// Interface for HTTP requests.
type Request interface {
Header(string) string
Host() string
Method() string
Path() string
Scheme() string
Param(string) string
Body() []byte
}
// Represents the HTTP request used in the given context.
type request struct {
reader *bufio.Reader
scheme string
host string
method string
path string
query string
headers []Header
body []byte
params []router.Parameter
}
// 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 ""
}
// Returns the requested host.
func (req *request) Host() string {
return req.host
}
// Returns the request method.
func (req *request) Method() string {
return req.method
}
// 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 ""
}
// Returns the requested path.
func (req *request) Path() string {
return req.path
}
// Returns either 'http', 'https', or an empty string.
func (req request) Scheme() string {
return req.scheme
}
// 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,
})
}
// Gets the request body.
func (req *request) Body() []byte {
return req.body
}