My package needs to be able to let my users define the fields backend database column name explicitly, if they want to.
By default I will use the fields name - but sometimes they will need to manually specify the column name, just like the JSON package - unmarshal uses the explicit name if required.
How can I consume this explicit value in my code? I don't even know what it's called so Google is really failing me at the moment.
Here's what JSON's unmarshal function needs for example:
type User struct {
Name string
LastName string `json:"last_name"`
CategoryId int `json:"category_id"`
}
What would I need to use something like this?
// Paprika is my package name.
type User struct {
Name string
LastName string `paprika:"last_name"`
CategoryId int `paprika:"category_id"`
}
My package will be constructing SQL queries and I can't just rely on the field's name - I need to be able to let them manually set the column name. So this is working with only the defined columns at the moment.
// Extracts resource information using reflection and
// saves field names and types.
func loadTypeToSchema(resource interface{}) {
resourceType := reflect.TypeOf(resource)
// Grab the resource struct Name.
fullName := resourceType.String()
name := fullName[strings.Index(fullName, ".")+1:]
// Grabs the resource struct fields and types.
fieldCount := resourceType.NumField()
fields := make(map[string]string)
for i := 0; i <= fieldCount-1; i++ {
field := resourceType.Field(i)
fields[field.Name] = field.Type.Name()
}
// Add resource information to schema map.
schema[name] = fields
}