Skip to content

Go reflection library to find struct field by its tag

License

Notifications You must be signed in to change notification settings

scylladb/go-reflectx

Repository files navigation

Reflectx GoDoc Go Report Card Build Status

Package reflectx implements extensions to the standard reflect lib suitable for implementing marshalling and unmarshalling packages. The main Mapper type allows for Go-compatible named attribute access, including accessing embedded struct attributes and the ability to use functions and struct tags to customize field names.

This is a standalone version of reflectx package that originates from an SQL row to struct mapper sqlx. We are using it at Scylla gocqlx for scanning of CQL results to structs and slices.

Example

This example demonstrates usage of the reflectx package to automatically bind URL parameters to a request model.

type RequestContext struct {
	SessionID string `http:"sid"`
}

type SearchRequest struct {
	RequestContext
	Labels     []string `http:"l"`
	MaxResults int      `http:"max"`
	Exact      bool     `http:"x"`
}

func Search(w http.ResponseWriter, r *http.Request) {
	// URL /search?sid=id&l=foo&l=bar&max=100&x=true
	if err := r.ParseForm(); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	var data SearchRequest
	if err := bindParams(r, &data); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	log.Printf("%+v", data) // "RequestContext:{SessionID:id} Labels:[foo bar] MaxResults:100 Exact:true}"
}

See the full example in example_test.go.

License

Copyright (C) 2019 ScyllaDB

This project is distributed under the Apache 2.0 license. See the LICENSE file for details. It contains software from: