From 84361964471bffc9deb5cec9043877bccd544985 Mon Sep 17 00:00:00 2001 From: some Date: Mon, 7 Oct 2024 18:14:34 -0400 Subject: [PATCH] Add Header Parse method --- header.go | 38 +++++++++++++++++++++++++++++++++++++- prototype.go | 1 + 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/header.go b/header.go index 2811338..4ad100f 100644 --- a/header.go +++ b/header.go @@ -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 { diff --git a/prototype.go b/prototype.go index e5b5441..1e7f9d7 100644 --- a/prototype.go +++ b/prototype.go @@ -27,6 +27,7 @@ type ErrorResponse interface { HttpStatus() int ErrorResponse() []byte String() string + Error() string } type PrototypeErrorResponse interface {