mirror of
https://codeberg.org/VnPower/PixivFE
synced 2024-12-06 19:16:23 +01:00
78 lines
2.3 KiB
Go
78 lines
2.3 KiB
Go
// This file provides utilities for manipulating URL paths and query parameters.
|
|
package template
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// PartialURL represents a simplified URL with a path and query parameters.
|
|
type PartialURL struct {
|
|
Path string
|
|
Query map[string]string
|
|
}
|
|
|
|
// LowercaseFirstChar returns a string with the first character lowercased.
|
|
func LowercaseFirstChar(s string) string {
|
|
return strings.ToLower(s[0:1]) + s[1:]
|
|
}
|
|
|
|
// UnfinishedQuery builds a URL string from a PartialURL by including all query parameters except a specified key,
|
|
// which it leaves empty and places at the end of the query string.
|
|
//
|
|
// Useful for preparing a URL where the value for the key is appended later (e.g. during query parameter replacement).
|
|
func UnfinishedQuery(url PartialURL, key string) string {
|
|
// Start building the URL with the path
|
|
result := fmt.Sprintf("%s", url.Path)
|
|
// Flag to check if we are adding the first query parameter
|
|
first_query_pair := true
|
|
|
|
// Iterate over the query parameters, excluding the specified key
|
|
for k, v := range url.Query {
|
|
// Lowercase the first character of the key to standardize it
|
|
k = LowercaseFirstChar(k)
|
|
|
|
// Skip the specified key to handle it separately later
|
|
if k == key {
|
|
continue
|
|
}
|
|
|
|
// Skip parameters with empty values to avoid cluttering the URL
|
|
if v == "" {
|
|
continue
|
|
}
|
|
|
|
// Add '?' before the first query parameter, '&' before subsequent ones
|
|
if first_query_pair {
|
|
result += "?"
|
|
first_query_pair = false
|
|
} else {
|
|
result += "&"
|
|
}
|
|
// Append the key-value pair to the result
|
|
result += fmt.Sprintf("%s=%s", k, v)
|
|
}
|
|
|
|
// Append the specified key at the end with an empty value
|
|
// This ensures the key appears last in the query string and can be easily modified
|
|
var t string
|
|
if first_query_pair {
|
|
// No query parameters were added before, so use '?'
|
|
t = "?"
|
|
} else {
|
|
// Query parameters were added before, so use '&'
|
|
t = "&"
|
|
}
|
|
result += fmt.Sprintf("%s%s=", t, key)
|
|
|
|
return result
|
|
}
|
|
|
|
// ReplaceQuery constructs a URL string by replacing the value of the specified key in the query parameters.
|
|
//
|
|
// It uses UnfinishedQuery to build the base URL and appends the new value for the key at the end.
|
|
func ReplaceQuery(url PartialURL, key string, value string) string {
|
|
// Build the unfinished query and append the new value for the key
|
|
return UnfinishedQuery(url, key) + value
|
|
}
|