73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package router
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
"strings"
|
|
)
|
|
|
|
type Header map[string][]string
|
|
|
|
func (h Header) Parse(data any) {
|
|
if h == nil {
|
|
h = make(Header)
|
|
}
|
|
d := reflect.ValueOf(data)
|
|
if d.Kind() != reflect.Struct {
|
|
panic(fmt.Errorf("expected struct input for data"))
|
|
}
|
|
for i := 0; i < d.NumField(); i++ {
|
|
key := d.Type().Field(i).Tag.Get("header")
|
|
if key == "" {
|
|
continue
|
|
}
|
|
v := make([]string, 0)
|
|
val := d.Field(i)
|
|
if val.Kind() == reflect.Pointer || val.Kind() == reflect.Interface {
|
|
val = val.Elem()
|
|
}
|
|
if val.Kind() == reflect.Slice || val.Kind() == reflect.Array {
|
|
for j := 0; j < val.Len(); j++ {
|
|
item := val.Index(j)
|
|
if item.Kind() == reflect.Pointer || item.Kind() == reflect.Interface {
|
|
item = item.Elem()
|
|
}
|
|
v = append(v, fmt.Sprint(item.Interface()))
|
|
}
|
|
} else {
|
|
v = append(v, fmt.Sprint(val.Interface()))
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h Header) Get(key string) (value string) {
|
|
v, ok := h[key]
|
|
if !ok {
|
|
return
|
|
}
|
|
return strings.Join(v, ", ")
|
|
}
|
|
|
|
func (h Header) Set(key string, value string) {
|
|
h[key] = []string{value}
|
|
}
|
|
|
|
func (h Header) Add(key string, value string) {
|
|
h[key] = append(h[key], value)
|
|
}
|
|
|
|
func (h Header) Merge(header Header) {
|
|
for key, value := range header {
|
|
if _, exists := h[key]; exists {
|
|
continue
|
|
}
|
|
h[key] = value
|
|
}
|
|
}
|
|
|
|
func (h Header) MergeOverwrite(header Header) {
|
|
for key, value := range header {
|
|
h[key] = value
|
|
}
|
|
}
|