Created
January 30, 2024 01:29
-
-
Save marcoscouto/0f9c6908e85abee3ec7239fe6c042c61 to your computer and use it in GitHub Desktop.
Golang - Capture Chi query params with reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"net/http" | |
"reflect" | |
"github.com/go-chi/chi/v5" | |
) | |
const paramTag = "param" | |
func main() { | |
r := chi.NewRouter() | |
r.Get("/", func(w http.ResponseWriter, r *http.Request) { | |
params := captureParams[Params](r) | |
marshal, _ := json.Marshal(params) | |
w.Header().Set("Content-Type", "application/json") | |
w.Write(marshal) | |
}) | |
http.ListenAndServe(":3000", r) | |
} | |
type Params struct { | |
ID string `json:"id" param:"id"` | |
Name string `json:"name" param:"name"` | |
} | |
func captureParams[E interface{}](r *http.Request) E { | |
values := r.URL.Query() | |
var e E | |
targetType := reflect.TypeOf(&e).Elem() | |
targetValue := reflect.ValueOf(&e).Elem() | |
for i := 0; i < targetType.NumField(); i++ { | |
field := targetType.Field(i) | |
tag := field.Tag.Get(paramTag) | |
paramValue := values.Get(tag) | |
targetValue.Field(i).SetString(paramValue) | |
} | |
return e | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment