Categorygithub.com/scylladb/go-reflectx
modulepackage
1.0.1
Repository: https://github.com/scylladb/go-reflectx.git
Documentation: pkg.go.dev

# README

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:

# Functions

CamelToSnakeASCII converts camel case strings to snake case.
Deref is Indirect for reflect.Types.
FieldByIndexes returns a value for the field given by the struct traversal for the given value.
FieldByIndexesReadOnly returns a value for a particular struct traversal, but is not concerned with allocating nil pointers because the value is going to be used for reading and not setting.
NewMapper returns a new mapper using the tagName as its struct field tag.
NewMapperFunc returns a new mapper which optionally obeys a field tag and a struct field name mapper func given by f.
NewMapperTagFunc returns a new mapper which contains a mapper for field names AND a mapper for tag values.

# Structs

A FieldInfo is metadata for a struct field.
Mapper is a general purpose mapper of names to struct fields.
A StructMap is an index of field metadata for a struct.