Added more tests

This commit is contained in:
2024-03-27 20:41:27 +01:00
parent 98e1a47328
commit b6c208c75b
7 changed files with 211 additions and 144 deletions

View File

@ -160,29 +160,8 @@ func (s *server) handleConnection(conn net.Conn) {
// handleRequest handles the given request.
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
ctx.scheme, ctx.host, ctx.path, ctx.query = parseURL(url)
err := s.handlers[0](ctx)
@ -190,11 +169,7 @@ func (s *server) handleRequest(ctx *context, method string, url string, writer i
s.errorHandler(ctx, err)
}
_, err = fmt.Fprintf(writer, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n%s\r\n%s", ctx.status, "OK", len(ctx.body), ctx.response.headerText(), ctx.body)
if err != nil {
s.errorHandler(ctx, err)
}
fmt.Fprintf(writer, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n%s\r\n%s", ctx.status, "OK", len(ctx.body), ctx.response.headerText(), ctx.body)
}
// newContext allocates a new context with the default state.
@ -210,3 +185,31 @@ func (s *server) newContext() *context {
},
}
}
// parseURL parses a URL and returns the scheme, host, path and query.
func parseURL(url string) (scheme string, host string, path string, query string) {
schemePos := strings.Index(url, "://")
if schemePos != -1 {
scheme = url[:schemePos]
url = url[schemePos+len("://"):]
}
pathPos := strings.IndexByte(url, '/')
if pathPos != -1 {
host = url[:pathPos]
url = url[pathPos:]
}
queryPos := strings.IndexByte(url, '?')
if queryPos != -1 {
path = url[:queryPos]
query = url[queryPos+1:]
return
}
path = url
return
}