-
-
Save meetme2meat/2ff1004baef56a18b87de0e415ba43a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql/driver" | |
"encoding/json" | |
"fmt" | |
"time" | |
"github.com/jinzhu/gorm" | |
_ "github.com/jinzhu/gorm/dialects/postgres" | |
) | |
var DB *gorm.DB | |
var dberr error | |
type Date struct { | |
time.Time | |
} | |
type CustomerBroker struct { | |
gorm.Model | |
StartDate Date `gorm:"type:date,column:start_date" json:"start_date"` | |
EndDate Date `gorm:"type:date,column:end_date" json:"end_date"` | |
} | |
func (d *Date) UnmarshalJSON(b []byte) (err error) { | |
if b[0] == '"' && b[len(b)-1] == '"' { | |
b = b[1 : len(b)-1] | |
} | |
// take care of null.. | |
if len(b) == 0 || string(b) == "null" { | |
d.Time = time.Time{} | |
return | |
} | |
d.Time, err = time.Parse("2006-01-02", string(b)) | |
return | |
} | |
func (d Date) Scan(b interface{}) (err error) { | |
// switch b.(type) { | |
// case nil: | |
// d.Time = time.Time{} | |
// case string: | |
// d.Time, err = time.Parse("2006-01-02", b.(string)) | |
// } | |
return | |
} | |
func (d Date) Value() (driver.Value, error) { | |
// check if the date was not set.. | |
if d.Time.IsZero() { | |
return nil, nil | |
} | |
return d.Time.Format("2006-01-02"), nil | |
} | |
func init() { | |
DB, dberr = gorm.Open("postgres", "host=127.0.0.1 port=5432 user=admin dbname=repl_test sslmode=disable") | |
if dberr != nil { | |
panic(dberr) | |
} | |
} | |
func main() { | |
record := CustomerBroker{} | |
data := []byte(`{"start_date": "2019-05-29", "end_date": null}`) | |
err := json.Unmarshal(data, &record) | |
if err != nil { | |
panic(err) | |
} | |
DB.Create(&record) | |
fmt.Println(DB.Error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment