Added URL parsing

This commit is contained in:
2024-03-27 14:06:13 +01:00
parent fff7b6ae47
commit 98e1a47328
3 changed files with 126 additions and 12 deletions

View File

@ -70,11 +70,9 @@ func (s *server) Get(path string, handler Handler) {
// Request performs a synthetic request and returns the response.
// This function keeps the response in memory so it's slightly slower than a real request.
// However it is very useful inside tests where you don't want to spin up a real web server.
func (s *server) Request(method string, path string, body io.Reader) Response {
func (s *server) Request(method string, url string, body io.Reader) Response {
ctx := s.newContext()
ctx.method = method
ctx.path = path
s.handleRequest(ctx, method, path, io.Discard)
s.handleRequest(ctx, method, url, io.Discard)
return ctx.Response()
}
@ -148,10 +146,10 @@ func (s *server) handleConnection(conn net.Conn) {
lastSpace = len(message)
}
path := message[space+1 : lastSpace]
url := message[space+1 : lastSpace]
ctx := s.pool.Get().(*context)
s.handleRequest(ctx, method, path, conn)
s.handleRequest(ctx, method, url, conn)
ctx.body = ctx.body[:0]
ctx.params = ctx.params[:0]
ctx.handlerCount = 0
@ -161,8 +159,29 @@ func (s *server) handleConnection(conn net.Conn) {
}
// handleRequest handles the given request.
func (s *server) handleRequest(ctx *context, method string, path string, writer io.Writer) {
func (s *server) handleRequest(ctx *context, method string, url string, writer io.Writer) {
schemePos := strings.Index(url, "://")
schemeEnd := 0
if schemePos != -1 {
schemeEnd = schemePos + len("://")
} else {
schemePos = 0
}
pathPos := strings.IndexByte(url[schemeEnd:], '/')
if pathPos == -1 {
return
}
scheme := url[:schemePos]
host := url[schemeEnd : schemeEnd+pathPos]
path := url[schemeEnd+pathPos:]
ctx.method = method
ctx.scheme = scheme
ctx.host = host
ctx.path = path
err := s.handlers[0](ctx)