router/header.go
2024-10-07 18:34:43 -04:00

74 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, ok := d.Type().Field(i).Tag.Lookup("header")
if !ok || 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.Sprintf("%s", item.Interface()))
}
} else {
v = append(v, fmt.Sprintf("%s", val.Interface()))
}
h[key] = v
}
}
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
}
}