Home > database >  Go time.Time to postgresql timestamptz not able to save with time.Now()
Go time.Time to postgresql timestamptz not able to save with time.Now()

Time:01-14

Hi I am new to golang and I am trying to insert a time.Now() value for a time.Time type of variable The weired part is that i am neither getting an error nor having the commit proccessed rather the execution of the code is been stopped when i try to insert it. Can someone please help me what should be the value that I should be trying?

db: alter table abc add column created timestamptz NULL;

struct { created time.Time db:"created" }

value been set before the insert is created = time.Now()

I expect the db to be saved with the new record

CodePudding user response:

Thank you @robbieperry22. In my case I was missing the capitalization of the C while defining my field inside my struct. As per my new learning the feild wasnt been exported lacking the capitilization im not deleting this question hoping someone like me new to golang to be benefited with it :) Cheers and Thank you. Solution credits : RobbiePerry22 A bit more detailed explanation: stackoverflow.com/questions/24837432/capitals-in-struct-fields

CodePudding user response:

In order for any external library to be able to look at your struct fields, they need to be exported, i.e. the name must start with a capital letter.

Since your definition defines the created time with a lower case letter, only code inside your package can see that field. This is why your database interface is setting "created" to NULL - as far as it knows, no value was ever provided for that field.

type Foo struct { 
    Created time.Time db:"created"
}

Note: if you happen to be using GORM to interface with your database, it actually supports what you are trying to do by default, simply by naming the struct field CreatedAt: https://gorm.io/docs/conventions.html#CreatedAt

  • Related