Mapping one type to another - go

Let's say I have the following types.
type Contract struct {
Id string `json:"id" gorm:"column:uuid"`
Name string `json:"name" gorm:"column:name"`
Description string `json:"descr" gorm:"column:descr"`
ContractTypeId int `json:"contract_type_id" gorm:"column:contract_type_id"`
}
type ContractModel struct {
Id string `json:"id" gorm:"column:uuid"`
Name string `json:"name" gorm:"column:name"`
Description string `json:"descr" gorm:"column:descr"`
}
I have a SQL query using gorm to scan results into a contract object.
How can I map the values from the contract object into contractModel object?
I tried using the package go-automapper as such:
automapper.Map(contract, ContractModel{})
I want to drop the ContractTypeId.
Can I do this for multiple types in a list?
var contractModels []ContractModel
automapper.Map(contracts, &contractModels)

You can do either:
models := []ContractModel{}
automapper.Map(contracts, &models)
Or call automapper.Map in a loop:
models := make([]ContractModel, len(contracts))
for i := range contracts {
automapper.Map(contracts[i], &models[i])
}
You should be aware that automapper uses reflection behind the scenes and thus is much slower than straight forward non-polymorphic copying like #ThinkGoodly suggests. It's a totally fine solution if performance isn't top priority though.

Related

GORM foreign keys without embedded struct

So, using GORM I realize that to use foreign keys, I have to embed the struct in another struct, otherwise gorm won't recognize the relationship like this:
type People struct {
ID int
Name string
Card []Card
}
type Card struct {
ID int
Name string
PeopleID int
}
But, i don't actually want this embeding system. For me, it becomes more troublesome to do sanitization when developing REST apis. So, is there a way to tell GORM about the relationship without actually having to have an embedded struct onto another? Like:
type People struct {
ID int
Name string
//No `Card` object here
}
type Card struct {
ID int
Name string
PeopleID int `gorm:"foreignKey:People.ID` //Something like this
}

Control over unexported struct fields

So this is my first question in stackoverflow. :)
We have defined a struct in org package like below:
type Employee struct {
FirstName, LastName string
salary int
}
and then in main.go file, we are initializing the struct like below:
func main() {
ross := Employee {
FirstName: "Ross",
LastName: "Geller",
}
fmt.Println(ross)
}
The output will be like below:
{Ross Geller 0}
As salary field is not exported from the Employee struct type, so it's displaying the zero value of int. An end-user will assume that the salary of this employee is 0.
So is there any way to control the unexported fields?
What is the best approach to deal with such a problem in a real-time scenario?
Is this really a problem?
If you're really worried about it, you can override the .String of Employee:
https://play.golang.org/p/PncEOGVP2HP
func (e Employee) String() string {
return fmt.Sprintf("%v", struct{
FirstName string
LastName string
}{e.FirstName, e.LastName})
}
But in reality, are they going to be seeing the output from the console of your program? Most likely this is a non-issue.
Well, If you want to initialize the field you can always write an exported function or method to do that such as
func New(first,last,salary string) Employee{
//...
}
The reason why you can have unexported types is to be able to create something called an opaque type.
You can have methods on your data setters and getters and do complex things without worrying about user braking the internal state of your data.
Imagine you are writing a drawing app and you have a painter Struct which keeps track of cursor and current color and stuff. You really would not want your user to be able to mess with your painter manually. that would break everything.
So the user creates the painter through an initializer and passes it around as a Painter type and using methods such as moveTo,lineTo which updates the state internally.

Go struct separation best practices

I am trying to figure out a decent approach toward dealing with multiple uses for a struct. Let me explain the scenario.
I have a struct that represents the Model in gorm. In the current implementation, I have validation bound to this struct so when a request hits the endpoint I would validate against the model's struct. This works fine for most cases. But then there are some instances where I want to have more control over the request and the response.
This is possible by introducing a few additional internal structs that will parse the request and response. And I can decouple the validation from the model into the request specific struct. I am trying to figure out what the best practice is around these patterns. Pretty sure a lot of peeps would have faced a similar situation.
// Transaction holds the transaction details.
type Transaction struct {
Program Program
ProgramID uuid.UUID
Type string
Value float64
Reference string
}
// TransactionRequest for the endpoint.
type TransactionRequest struct {
ProgramKey string `json:"program_key" validator:"required"`
Type string `json:"type" validator:"required,oneof=credit debit"`
Value float64 `json:"value" validator:"required,numeric"`
Reference string `json:"reference" validator:"required"`
}
Update:
I managed to find a balance by introducing additional tags for update requests, I wrote about how I achieved it here
I faced similar problem and for solving that, defined a method for validating and didn't use tags. I had to, because I follow DDD and we should validate in service layer not API layer.
here is a sample of my apporach:
type Station struct {
types.GormCol
CompanyID types.RowID `gorm:"not null;unique" json:"company_id,omitempty"`
CompanyName string `gorm:"not null;unique" json:"company_name,omitempty"`
NodeCode uint64 `json:"node_code,omitempty"`
NodeName string `json:"node_name,omitempty"`
Key string `gorm:"type:text" json:"key,omitempty"`
MachineID string `json:"machine_id,omitempty"`
Detail string `json:"detail,omitempty"`
Error error `sql:"-" json:"user_error,omitempty"`
Extra map[string]interface{} `sql:"-" json:"extra_station,omitempty"`
}
// Validate check the type of
func (p *Station) Validate(act action.Action) error {
fieldError := core.NewFieldError(term.Error_in_companys_form)
switch act {
case action.Save:
if p.CompanyName == "" {
fieldError.Add(term.V_is_required, "Company Name", "company_name")
}
if p.CompanyID == 0 {
fieldError.Add(term.V_is_required, "Company ID", "company_id")
}
}
if fieldError.HasError() {
return fieldError
}
return nil
}
file's address: https://github.com/syronz/sigma-mono/blob/master/model/station.model.go

How to omit some parameters of structure Gin gonic

I have big structure with more than 50 params
type Application struct {
Id int64 `json:"id"`
FullName string `json:"fullName,omitempty"`
ActualAddress string `json:"actualAddress,omitempty"`
.....
}
I use gin-gonic and when I return application I need to omit some params I've created a function which makes empty some params (playLink) and then gin returns me correct json (without unnecessary values). I heard that reflection isn't fast operation so in our case we can use a lot of ugly if-else or switch-cases. Is there any other solutions faster than reflecting and more beautiful than if-elses?
The thing is that structure params have non-empty values, so they wont by omitted by gin. That's why I've created function to make some params empty before return
The thing is, if you only want to zero a few fields, it's more readable to do it without a function, e.g.
app := Application{}
app.FullName, app.ActualAddress = "", ""
If you want to create a function for it, at least use variadic parameter, so it's easier to call it:
func zeroFields(application *Application, fields ...string) {
// ...
}
So then calling it:
zeroFields(&app, "FullName", "ActualAddress")
Yes, this will have to use reflection, so it's slower than it could be, and error prone (mistyped names can only be detected at runtime). If you want to avoid using reflection, pass the address of the fields:
func zeroFields(ps ...*string) {
for _, p := range ps {
*p = ""
}
}
This way you have compile-time guarantee that you type field names correctly, and that they have string type.
Calling it:
zeroFields(&application.FullName, &application.ActualAddress)
Try it on the Go Playground.
If I understand correctly: you want to return some values from your struct but not all of them? Perhaps a nested struct?
type Application struct {
ID struct {
ID int64 `json:"id"`
} `json:"id"`
Person struct {
Fullname string `json:"Fullname"
} `json:"person"
}
That should let you filter out the fields you want to use.

golang initilize inner struct object in nested structs

I have a nested struct
type Posts struct {
Id int
CreatedAt time.Time
Data struct {
Title string
UserName string
}
}
I want to create a Data object but var innerData Posts.Data doesn't seem to work. I don't want to create separate Data struct because I'm planning to avoid name collusions by having multiple structs which will have different inner structs named Data.
You can't. Posts.Data isn't the name of a type. The only thing you could do is var innerData struct{ ... }, which I'm sure you don't want to because then you would have repetition and need to make changes in two places. Otherwise, you have to give it a name. That name doesn't have to be Data, it can be PostData or something to make it unique.

Resources