2024-05-29 21:55:59 +03:00
|
|
|
package urlenc
|
|
|
|
|
|
|
|
import "fmt"
|
2024-05-30 09:30:25 +03:00
|
|
|
import "net/url"
|
2024-05-29 21:55:59 +03:00
|
|
|
|
2024-05-30 09:30:25 +03:00
|
|
|
type Values = url.Values
|
|
|
|
|
|
|
|
type Builder interface {
|
|
|
|
BuildQueryValues() Values
|
|
|
|
}
|
|
|
|
|
|
|
|
type Value[V any] struct {
|
2024-05-29 21:55:59 +03:00
|
|
|
Name string
|
2024-05-29 22:59:36 +03:00
|
|
|
Value V
|
|
|
|
}
|
2024-05-30 09:30:25 +03:00
|
|
|
func (value Value[V]) BuildQueryValues() Values {
|
|
|
|
values := Values{}
|
|
|
|
values.Add(
|
|
|
|
value.Name,
|
|
|
|
fmt.Sprintf("%v", value.Value),
|
|
|
|
)
|
|
|
|
return values
|
|
|
|
}
|
|
|
|
|
|
|
|
func (value Value[V]) String() string {
|
|
|
|
unesc, err := url.QueryUnescape(
|
|
|
|
value.BuildQueryValues().Encode(),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return unesc
|
2024-05-29 21:55:59 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
type Array[V any] struct {
|
|
|
|
Name string
|
|
|
|
Values []V
|
|
|
|
}
|
|
|
|
|
2024-05-30 09:30:25 +03:00
|
|
|
func (a Array[V]) BuildQueryValues() Values {
|
|
|
|
values := Values{}
|
2024-05-29 21:55:59 +03:00
|
|
|
for i, v := range a.Values {
|
2024-05-30 09:30:25 +03:00
|
|
|
values.Add(
|
|
|
|
fmt.Sprintf("%s[%d]", a.Name, i),
|
|
|
|
fmt.Sprintf("%v", v),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
return values
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a Array[V]) String() string {
|
|
|
|
unesc, err := url.QueryUnescape(
|
|
|
|
a.BuildQueryValues().Encode(),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
2024-05-29 21:55:59 +03:00
|
|
|
}
|
2024-05-30 09:30:25 +03:00
|
|
|
return unesc
|
2024-05-29 21:55:59 +03:00
|
|
|
}
|
|
|
|
|
2024-05-30 09:30:25 +03:00
|
|
|
func Join(builders ...Builder) Values {
|
|
|
|
ret := Values{}
|
|
|
|
for _, builder := range builders {
|
|
|
|
for k, v := range builder.BuildQueryValues() {
|
|
|
|
for _, jv := range v {
|
|
|
|
ret.Add(k, jv)
|
|
|
|
}
|
|
|
|
}
|
2024-05-29 22:59:36 +03:00
|
|
|
}
|
2024-05-30 09:30:25 +03:00
|
|
|
return ret
|
2024-05-29 22:59:36 +03:00
|
|
|
}
|
2024-07-30 00:43:03 +03:00
|
|
|
|
|
|
|
type FnArray[V any] struct {
|
|
|
|
Values []V
|
|
|
|
Fn func([]V, int) (string, string)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a FnArray[V]) BuildQueryValues() Values {
|
|
|
|
values := Values{}
|
|
|
|
for i := range a.Values {
|
|
|
|
k, v := a.Fn(a.Values, i)
|
|
|
|
values.Add(k, v)
|
|
|
|
}
|
|
|
|
return values
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a FnArray[V]) String() string {
|
|
|
|
unesc, err := url.QueryUnescape(
|
|
|
|
a.BuildQueryValues().Encode(),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return unesc
|
|
|
|
}
|