Add Header Parse method

This commit is contained in:
some 2024-10-07 18:14:34 -04:00
parent 0ceaf17c34
commit 8436196447
Signed by: some
GPG Key ID: 65D0589220B9BFC8
2 changed files with 38 additions and 1 deletions

View File

@ -1,9 +1,45 @@
package router
import "strings"
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 {

View File

@ -27,6 +27,7 @@ type ErrorResponse interface {
HttpStatus() int
ErrorResponse() []byte
String() string
Error() string
}
type PrototypeErrorResponse interface {