How can I add a new boolean property to a Golang struct and set the default value to true? - go

I have a user struct that corresponds to an entity. How can I add a new property active and set the default value to true?
Can I also set the value of that property to true for all existing entities by some easy method?
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
Bonus questions: I don't quite understand the syntax in the struct. What do the three columns represent? What do the JSON strings have ``around them?

//You can't change declared type.
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//Instead you construct a new one embedding existent
type ActiveUser struct {
User
Active bool
}
//you instantiate type literally
user := User{1, "John"}
//and you can provide constructor for your type
func MakeUserActive(u User) ActiveUser {
auser := ActiveUser{u, true}
return auser
}
activeuser := MakeUserActive(user)
You can see it works https://play.golang.org/p/UU7RAn5RVK

You have to set the default value as true at the moment when you are passing the struct type to a variable, but this means you need to extend that struct with a new Active field.
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
Active bool
}
user := User{1, "John", true}
json:"id" means that you are mapping the json decoded object field to the field id in your struct type. Practically you are deserialize the json string into object fields which later you can map to their specific field inside the struct.

Related

How can we create a similar model field type to Django field.choices in GORM/Golang

I am trying to create a struct field, and limit its values to a list of values i.e,
state =["locked", "unlocked"]
now in Django models we use the field choices i.e
class Book(models.Model):
LOCKED = 'LK'
UNLOCKED = 'UN'
STATE = [
('LK', 'Locked'),
('UL', 'Unlocked'),
]
book_state = models.CharField(choices=STATE, default=LOCKED)
trying to replicate the above using a gorm.model struct data type in Go.
Solution: create a custom golang type with string and add it as gorm model field
type BookState string
const (
Locked BookState = "locked"
Unlocked BookState = "unlocked"
)
Then create your gorm struct model fields
type Book struct {
Name string `json:"name" validate:"required"`
State BookState `json:"state" validate: "required"`
....
}

How to access the fields of this struct in Golang

I'm new to Golang and I need to know how to access the value from a struct of the format:
type CurrentSkuList struct {
SubscriptionNumber string `json:"subscriptionNumber`
Quantity int `json:"quantity"`
SubscriptionProducts []struct {
ID int `json:"id"`
ActiveStartDate int `json:"activeStartDate"`
ActiveEndDate int `json:"activeEndDate"`
Status string `json:"status"`
Sku string `json:"sku"`
ChildIDs []int `json:"childrenIds"`
} `json:"subscriptionProducts"`
}
For example, if I have a variable currentSkus of type CurrentSkuList and I need to access only Sku and Status values, is there a way to do something like:
currentSkus.SubscriptionProducts.Sku?
EDIT! When I try to access currentSkus.Quantity I get a compiler error undefined (type []util.CurrentSkuList has no field or method Quantity).
Yeah, there is a way. You can access by the . syntax you proposed. In this case, CurrentSkuList is returning an slice of SubscriptionProduct, you know that because of the [] struct part. Then you would have to access to the data this way:
currentSkus.SubscriptionProducts[index].Sku

How can I choose which struct member to update at runtime?

Say I have a struct in Go that looks like this:
LastUpdate struct {
Name string `yaml:"name"`
Address string `yaml:"address"`
Phone string `yaml:"phone"`
}
Now say I want to create a function that accepts the name of the field (eg. "Phone") and then updates that field to a value, like today's date.
How can I build the function in a way that it will accept the name of the field and update that field in the struct?
I know that I could do an IF clause for each scenario (if field == "Phone") {var.LastUpdate.Phone = time.Now().Date()}, but I'd like to build this function so that I don't have to go add an IF clause every time I add a new member to this struct in the future. Thoughts?
Use the reflect package to set a field by name.
// setFieldByName sets field with given name to specified value.
// The structPtr argument must be a pointer to a struct. The
// value argument must be assignable to the field.
func setFieldByName(structPtr interface{}, name string, value interface{}) error {
v := reflect.ValueOf(structPtr)
v = v.Elem() // deference pointer
v = v.FieldByName(name) // get field with specified name
if !v.IsValid() {
return errors.New("field not found")
}
v.Set(reflect.ValueOf(value))
return nil
}
Use it like this:
var lu LastUpdate
setFieldByName(&lu, "Name", "Russ Cox")
Run it on the Playground

Gorm w/ Postgres has a nested struct as JSON

I am using GORM and I want to store the following struct in Postgres:
// Value GoDoc
type Value struct {
Name string
Place string
Value interface{}
}
// SharedConfig stores tenant-wide shared values
type SharedConfig struct {
gorm.Model
TenantID string
ProgramID *string
Name string
Value Value
}
I want to store SharedConfig in my DB and want the Value column to be stored as JSON, is this possible? I've only seen uses of the json column type as postgres.Jsonb

Golang Decode a BSON with special character Keys to a struct

I have a Golang struct called Person where all the properties have to be exported:
type Person struct {
Id string
Name string
}
Now I need to encode my MongoDB BSON response to this Person struct. The BSON looks like:
{
"_id": "ajshJSH78N",
"Name": "Athavan Kanapuli"
}
The Golang code to encode the BSON is:
mongoRecord := Person{}
c := response.session.DB("mydb").C("users")
err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)
The Problem:
_id is not getting encoded into Id
If I change the Person property into _Id, then it won't be exported.
How can I solve this problem?
Define your struct with json tag-
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
I tried to put a json tag like ,
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
But still it didn't work. Because the Mongodb returns '_id' which is of type bson.ObjectId . Hence changing the Struct tag to bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,
type Person struct {
Id bson.ObjectId `bson:"_id"`
Name string
UserName string
IsAdmin bool
IsApprover bool
}
And It works!

Resources