You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.6 KiB
78 lines
1.6 KiB
package nwweb
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
type Request struct {
|
|
httpRequest *http.Request
|
|
Body body
|
|
Headers headers
|
|
QueryParameters queryParameters
|
|
Form form
|
|
}
|
|
|
|
func NewRequest(method, urlFmt string, args ...any) *Request {
|
|
var httpRequest *http.Request
|
|
if len(args) > 0 {
|
|
httpRequest, _ = http.NewRequest(method, fmt.Sprintf(urlFmt, args...), nil)
|
|
} else {
|
|
httpRequest, _ = http.NewRequest(method, urlFmt, nil)
|
|
}
|
|
|
|
r := &Request{
|
|
httpRequest: httpRequest,
|
|
Headers: newHeaders(httpRequest),
|
|
QueryParameters: newQueryParameters(httpRequest),
|
|
Form: newForm(httpRequest),
|
|
}
|
|
|
|
r.Body = newBody(r, new(bytes.Buffer))
|
|
return r
|
|
}
|
|
|
|
func newRequestServer(httpRequest *http.Request) *Request {
|
|
r := &Request{
|
|
httpRequest: httpRequest,
|
|
Headers: newHeaders(httpRequest),
|
|
QueryParameters: newQueryParameters(httpRequest),
|
|
Form: newForm(httpRequest),
|
|
}
|
|
|
|
r.Body = newBody(r, httpRequest.Body)
|
|
return r
|
|
}
|
|
|
|
func (r Request) Method() string {
|
|
return r.httpRequest.Method
|
|
}
|
|
|
|
func (r Request) Cookie(key string) *http.Cookie {
|
|
cookie, _ := r.httpRequest.Cookie(key)
|
|
return cookie
|
|
}
|
|
|
|
func (r Request) IP() net.IP {
|
|
if ipString, _, err := net.SplitHostPort(r.httpRequest.RemoteAddr); err == nil {
|
|
return net.ParseIP(ipString)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r Request) SetCookie(cookie *http.Cookie) {
|
|
r.httpRequest.AddCookie(cookie)
|
|
}
|
|
|
|
func (r *Request) finalize() {
|
|
r.httpRequest.ContentLength = int64(r.Body.Len())
|
|
r.httpRequest.Body = r.Body
|
|
r.httpRequest.GetBody = func() (io.ReadCloser, error) {
|
|
return r.Body, nil
|
|
}
|
|
}
|