Skip to content

Instantly share code, notes, and snippets.

@marcoscouto
Created January 30, 2024 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoscouto/0f9c6908e85abee3ec7239fe6c042c61 to your computer and use it in GitHub Desktop.
Save marcoscouto/0f9c6908e85abee3ec7239fe6c042c61 to your computer and use it in GitHub Desktop.
Golang - Capture Chi query params with reflection
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