Added support for URL fragments

Added support for a URL's fragment/anchor to `split_url` & `join_url` in `core:net` plus 4 new tests to cover it.
This commit is contained in:
blob1807
2024-04-13 00:39:32 +10:00
parent 4240e0025e
commit c753711d86
2 changed files with 80 additions and 23 deletions
+15 -2
View File
@@ -21,7 +21,7 @@ import "core:strconv"
import "core:unicode/utf8"
import "core:encoding/hex"
split_url :: proc(url: string, allocator := context.allocator) -> (scheme, host, path: string, queries: map[string]string) {
split_url :: proc(url: string, allocator := context.allocator) -> (scheme, host, path: string, queries: map[string]string, fragment: string) {
s := url
i := strings.index(s, "://")
@@ -30,6 +30,12 @@ split_url :: proc(url: string, allocator := context.allocator) -> (scheme, host,
s = s[i+3:]
}
i = strings.index_byte(s, '#')
if i != -1 {
fragment = s[i+1:]
s = s[:i]
}
i = strings.index(s, "?")
if i != -1 {
query_str := s[i+1:]
@@ -62,7 +68,7 @@ split_url :: proc(url: string, allocator := context.allocator) -> (scheme, host,
return
}
join_url :: proc(scheme, host, path: string, queries: map[string]string, allocator := context.allocator) -> string {
join_url :: proc(scheme, host, path: string, queries: map[string]string, fragment: string, allocator := context.allocator) -> string {
b := strings.builder_make(allocator)
strings.builder_grow(&b, len(scheme) + 3 + len(host) + 1 + len(path))
@@ -95,6 +101,13 @@ join_url :: proc(scheme, host, path: string, queries: map[string]string, allocat
i += 1
}
if fragment != "" {
if fragment[0] != '#' {
strings.write_byte(&b, '#')
}
strings.write_string(&b, strings.trim_space(fragment))
}
return strings.to_string(b)
}