Cast value from JSON when unmarshalling to struct - go

I have this JSON API that returns the delivery date as a UNIX timestamp. I would prefer using Time in the rest of the application. The following works but doesn't feel very Go like.
type Delivery struct {
Time string `json:"time"`
}
func timestampToTime(s string) time.Time {
i, _ := strconv.ParseInt(s, 10, 64)
returns time.Unix(i, 0)
}
fmt.Println(timestampToTime(Delivery.Time))
// 2019-02-17 11:55:00 +0100 CET
Is there a way to cast an incoming value in a struct?

You can do something very similar to the custom JSON Unmarshal method described here:
http://choly.ca/post/go-json-marshalling/
Assuming that the JSON contains a string in your case this would look like this:
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"time"
)
const input = `{"time": "946684799"}`
type Delivery struct {
Time time.Time `json:"time"`
}
func (d *Delivery) UnmarshalJSON(data []byte) error {
type Alias Delivery
aux := &struct {
Time string `json:"time"`
*Alias
}{
Alias: (*Alias)(d),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
i, err := strconv.ParseInt(aux.Time, 10, 64)
if err != nil {
return err
}
d.Time = time.Unix(i, 0)
return nil
}
func main() {
var delivery Delivery
err := json.Unmarshal([]byte(input), &delivery)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Println(delivery.Time)
}
https://play.golang.org/p/mdOmUO2EDIR

Related

Golang RCP call hanging

I have a back-end app and a front-end, both in Go. I am trying to make them talk via rpc.
back-end main.go
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/rpc"
"time"
)
type Application struct {
config struct {
server struct {
port int
network string
}
}
}
type MusicProject struct {
Id string
CreatedTime time.Time
LastEditedTime time.Time
Title string
Year int
Status string
Description string
ChoirRollup string
}
func main() {
var app Application
app.config.server.port = 5002
app.config.server.network = "tcp"
if err := rpc.Register(new(Application)); err != nil {
log.Fatal(err)
}
rpc.HandleHTTP()
// start the rpc server
log.Println("Starting server port", app.config.server.port)
l, err := net.Listen("tcp", fmt.Sprintf(":%v", app.config.server.port))
if err != nil {
log.Fatal(err)
}
if err = http.Serve(l, nil); err != nil {
log.Fatal(err)
}
}
func (app *Application) GetMusicProjectById(id string, model *MusicProject) error {
musicProject := MusicProject{
Id: id,
CreatedTime: time.Now(),
LastEditedTime: time.Now(),
Title: "Test Project",
Year: 2020,
Status: "Completed",
Description: "Short project Description",
ChoirRollup: "Best Choir",
}
model = &musicProject
return nil
}
front-end rpc call
package main
import (
"log"
"net/rpc"
"time"
)
type MusicProject struct {
Id string
CreatedTime time.Time
LastEditedTime time.Time
Title string
Year int
Status string
Description string
ChoirRollup string
}
func main() {
dial, err := rpc.Dial("tcp", "localhost:5002")
if err != nil {
log.Println(err)
}
projectID := "some_id_123"
var musicProject MusicProject
err = dial.Call("Application.GetMusicProjectById", projectID, &musicProject)
if err != nil {
log.Println(err)
}
log.Println(musicProject)
}
Once the client method is call, the call hanged indefinite with out sending back any error, so quite difficult to debug.
Do you have any suggestion for debugging? Do you see anything wrong in my code?
Thank you for your help!
Your server is serving HTTP:
if err = http.Serve(l, nil); err != nil {
log.Fatal(err)
}
But your client is using straight TCP (HTTP runs over TCP but adds another layer):
err = dial.Call("Application.GetMusicProjectById", projectID, &musicProject)
So to fix your issue you need to change one side or the other. For example change the server to:
rpc.Accept(l)
(alternatively you could use rpc.DialHTTP in the client)
There are a couple of other issues with your code (the main one being the way you set the response in the back-end). The following works for me (have not put much effort into making it tidy or testing!).
server
package main
import (
"fmt"
"log"
"net"
"net/rpc"
"time"
)
type MusicProject struct {
Id string
CreatedTime time.Time
LastEditedTime time.Time
Title string
Year int
Status string
Description string
ChoirRollup string
}
type Application struct {
}
func (app *Application) GetMusicProjectById(id string, model *MusicProject) error {
*model = MusicProject{
Id: id,
CreatedTime: time.Now(),
LastEditedTime: time.Now(),
Title: "Test Project",
Year: 2020,
Status: "Completed",
Description: "Short project Description",
ChoirRollup: "Best Choir",
}
return nil
}
func main() {
const port = 5002
if err := rpc.Register(new(Application)); err != nil {
log.Fatal(err)
}
// start the rpc server
log.Println("Starting server on port:", port)
l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatal(err)
}
rpc.Accept(l)
}
client
package main
import (
"log"
"net/rpc"
"time"
)
type MusicProject struct {
Id string
CreatedTime time.Time
LastEditedTime time.Time
Title string
Year int
Status string
Description string
ChoirRollup string
}
func main() {
dial, err := rpc.Dial("tcp", "localhost:5002")
if err != nil {
log.Fatal(err)
}
projectID := "some_id_123"
var musicProject MusicProject
err = dial.Call("Application.GetMusicProjectById", projectID, &musicProject)
if err != nil {
log.Fatal("error:", err)
}
log.Println(musicProject)
}

String to float64 receiving format ".01"

If I receive from an API a string obeying the format of ".01", and I have a struct like this:
type Mystruct struct {
Val float64 json:"val,string"
}
In this case, I receive trying to unmarshal val into float64. Is there a way I can accomplish this?
Add a string field to capture the string value:
type Mystruct struct {
Val float64 `json:"-"`
XVal string `json:"val"`
}
Unmarshal the JSON document. Convert the string value to a float value:
var v Mystruct
err := json.Unmarshal([]byte(data), &v)
if err != nil {
log.Fatal(err)
}
v.Val, err = strconv.ParseFloat(v.XVal, 64)
if err != nil {
log.Fatal(err)
}
I recommand defining a type alias which you can use it anywhere.
package main
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
type MyFloat64 float64
func (f *MyFloat64) UnmarshalJSON(data []byte) error {
raw := string(data)
raw = strings.TrimPrefix(raw, "\"")
raw = strings.TrimSuffix(raw, "\"")
if parsedFloat, err := strconv.ParseFloat(raw, 64); err != nil {
return err
} else {
*f = MyFloat64(parsedFloat)
return nil
}
}
type MyObj struct {
Val1 MyFloat64
Val2 string
}
func main() {
j := `{"Val1":"0.01", "Val2":"0.01"}`
o := MyObj{}
err := json.Unmarshal([]byte(j), &o)
if err != nil {
fmt.Println(err)
} else {
b, _ := json.Marshal(o)
fmt.Println("in:", j)
fmt.Println("out:", string(b))
}
}
output:
in: {"Val1":"0.01", "Val2":"0.01"}
out: {"Val1":0.01,"Val2":"0.01"}

Transform struct to slice struct

I'm trying to select a struct by string input and then depending on the return JSON Object or Array, unmarshall the JSON. Is it correct to think of a way to reflect the struct to slice struct? if so how to do that with reflection?
Regards,
Peter
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type NameStruct struct {
Name string
}
func main() {
jsonData := []byte(`[{"name":"james"},{"name":"steven"}]`)
returnModel := InitializeModel("NameStruct", jsonData)
fmt.Println(returnModel)
jsonData = []byte(`{"name":"james"}`)
returnModel = InitializeModel("NameStruct", jsonData)
fmt.Println(returnModel)
}
func getModelByName(modelType string) interface{} {
modelMap := make(map[string]interface{})
modelMap["NameStruct"] = new(NameStruct)
//don't want to do this
modelMap["arrNameStruct"] = new([]NameStruct)
return modelMap[modelType]
}
func InitializeModel(modelName string, jsonData []byte) interface{} {
switch IsArray(jsonData) {
case true:
// some conversion here, how?
returnModel := getModelByName("NameStruct")
if err := json.Unmarshal(jsonData, &returnModel); err != nil {
log.Println(err)
}
return returnModel
case false:
returnModel := getModelByName("NameStruct")
if err := json.Unmarshal(jsonData, &returnModel); err != nil {
log.Println(err)
}
return returnModel
}
return nil
}
func IsArray(jsonData []byte) bool {
return (bytes.HasPrefix(jsonData, []byte("["))) && (bytes.HasSuffix(jsonData, []byte("]")))
}
Expanding on my comment, you can create a Factory where pre-defined types are registered:
type Factory struct {
m map[string]reflect.Type
}
func (f *Factory) Register(v interface{}) {
vt := reflect.TypeOf(v)
n := vt.Name()
f.m[n] = vt
f.m["[]"+n] = reflect.SliceOf(vt) // implicitly register a slice of type too
}
these types can be looked up by name at runtime and initialized with JSON data:
func (f *Factory) Make(k string, bs []byte) (interface{}, error) {
vt, ok := f.m[k]
if !ok {
return nil, fmt.Errorf("type %q not registered", k)
}
pv := reflect.New(vt).Interface()
err := json.Unmarshal(bs, pv)
if err != nil {
return nil, err
}
return pv, nil
}
To use:
type Place struct {
City string `json:"city"`
}
factory.Register(Place{})
p, err := factory.Make("Place", []byte(`{"city":"NYC"}`))
fmt.Printf("%#v\n", p) // &main.Place{City:"NYC"}
Slices also work:
ps, err := factory.Make("[]Place", []byte(`[{"city":"NYC"},{"city":"Dublin"}]`))
fmt.Printf("%#v\n", p, p) // &[]main.Place{main.Place{City:"NYC"}, main.Place{City:"Dublin"}}
Playground: https://play.golang.org/p/qWEdwk-YUug

Using a singleton database class with separate models and services packages

My question is similar to How to create singleton DB class in GoLang but I'm having trouble getting it to work with separate models and services packages.
project/lib/database/mysql.go:
package database
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type Manager struct {
*gorm.DB
}
var Mgr *Manager
func init() {
dsn := MysqlConnectionString("parseTime=true")
tablePrefix := "demo"
var err error
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return fmt.Sprintf("%v_%v", tablePrefix, defaultTableName)
}
db, err := gorm.Open("mysql", dsn)
if err != nil {
panic(err)
}
Mgr = &Manager{db}
}
project/lib/models/retailer_keys.go
package models
import (
"fmt"
"project/lib/database"
"time"
)
type RetailerKeysInterface interface {
RetailerKeys() ([]*RetailerKey, error)
}
type DB struct {
database.Manager
}
type RetailerKey struct {
Id int `json:"id"`
RetailerId int `json:"retailer_id"`
Key string `json:"key"`
Enabled *bool `json:"enabled"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
}
func (db *DB) RetailerKeys() ([]*RetailerKey, error) {
var keys []*RetailerKey
if err := db.Find(&keys).Error; err != nil {
return nil, err
}
return keys, nil
}
project/lib/services/retailer_keys.go
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/apigateway"
"gopkg.in/volatiletech/null.v6"
"project/lib/models"
"project/lib/services/api_keys"
)
func GetKeys() ([]*models.RetailerKey, error) {
var q models.RetailerKeysInterface
keys, err := q.RetailerKeys()
if err != nil {
return nil, err
}
return keys, nil
}
func CreateKey(id int) (models.RetailerKey, error) {
...
}
Then be able to use it in my main package like:
package main
import (
"context"
"encoding/json"
// "reflect"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
_ "project/lib/config"
"project/lib/services"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
statusCode := 200
keys, err := services.GetKeys()
if err != nil {
statusCode = 400
}
body, _ := json.Marshal(keys)
return events.APIGatewayProxyResponse{
Body: string(body),
StatusCode: statusCode,
}, nil
}
...
I'd like to be able to embed the relevant subset of the Manager type in my models.
EDIT:
Edited the question/code based on feedback in comments.
This gives me an error: runtime error: invalid memory address or nil pointer dereference.
I was definitely misunderstanding interfaces in go. After going through A Tour of Go it started to become clearer how it all fits together.
This is that I ended up doing for anyone that is going through the same thing. I'll leave the original question up so you can see the differences.
project/lib/database/mysql.go:
package database
import (
"fmt"
"log"
_ "github.com/go-sql-driver/mysql" // Needed for gorm
"github.com/jinzhu/gorm"
)
var Manager *gorm.DB
func init() {
var err error
dsn := MysqlConnectionString("parseTime=true")
tablePrefix := "qcommerce"
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return fmt.Sprintf("%v_%v", tablePrefix, defaultTableName)
}
Manager, err = gorm.Open("mysql", dsn)
if err != nil {
log.Fatal(err)
}
if err := Manager.DB().Ping(); err != nil {
log.Fatal(err)
}
}
project/lib/models/retailer_keys.go
package models
import (
"project/lib/database"
"time"
)
type QRetailerKeys interface {
Insert() error
Find() error
}
type RetailerKey struct {
ID int `json:"id"`
RetailerID int `json:"retailer_id"`
Retailer Retailer `json:"retailer"`
Key string `json:"key"`
Enabled bool `json:"enabled" gorm:"DEFAULT:true"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
}
// RetailerKeys returns a slice of all keys in table
func RetailerKeys() ([]*RetailerKey, error) {
var keys []*RetailerKey
if err := database.Manager.Find(&keys).Error; err != nil {
return nil, err
}
return keys, nil
}
func (r *RetailerKey) Find() error {
...
}
// Create a new key
func (r *RetailerKey) Create() error {
return database.Manager.Create(&r).Error
}
project/lib/services/retailer_keys.go
package services
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
// "github.com/aws/aws-sdk-go/service/apigateway"
"partners.drinks.com/lib/models"
"partners.drinks.com/lib/services/api_keys"
)
func sessionBuilder() *session.Session {
config := &aws.Config{
Region: aws.String("us-west-2"),
}
session := session.Must(session.NewSession(config))
return session
}
func GetKeys() ([]*models.RetailerKey, error) {
keys, err := models.RetailerKeys()
if err != nil {
return nil, err
}
return keys, nil
}
func CreateKey(id int) (models.RetailerKey, error) {
apikeys := &api_keys.ApiKeyBuilder{}
base64Key := apikeys.GenUUID().GenKey().Base64
var key = models.RetailerKey{
RetailerID: id,
Key: base64Key,
Enabled: func(b bool)
}
if err := key.Create(); err != nil {
return models.RetailerKey{}, err
}
...
return key, nil
}
I use it like:
package main
import (
"context"
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
_ "partners.drinks.com/lib/config"
"partners.drinks.com/lib/services"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
statusCode := 200
keys, err := services.GetKeys()
if err != nil {
statusCode = 400
}
body, _ := json.Marshal(keys)
return events.APIGatewayProxyResponse{
Body: string(body),
StatusCode: statusCode,
}, nil
}
...
Thanks to #mkopriva for the linked resources in the comments.

How to read a YAML file

I have an issue with reading a YAML file. I think it's something in the file structure but I can't figure out what.
YAML file:
conf:
hits:5
time:5000000
code:
type conf struct {
hits int64 `yaml:"hits"`
time int64 `yaml:"time"`
}
func (c *conf) getConf() *conf {
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
your yaml file must be
hits: 5
time: 5000000
your code should look like this:
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
)
type conf struct {
Hits int64 `yaml:"hits"`
Time int64 `yaml:"time"`
}
func (c *conf) getConf() *conf {
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
func main() {
var c conf
c.getConf()
fmt.Println(c)
}
the main error was capital letter for your struct.
Example
Using an upgraded version 3 of yaml package.
An example conf.yaml file:
conf:
hits: 5
time: 5000000
camelCase: sometext
The main.go file:
package main
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v3"
)
type myData struct {
Conf struct {
Hits int64
Time int64
CamelCase string `yaml:"camelCase"`
}
}
func readConf(filename string) (*myData, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
c := &myData{}
err = yaml.Unmarshal(buf, c)
if err != nil {
return nil, fmt.Errorf("in file %q: %w", filename, err)
}
return c, err
}
func main() {
c, err := readConf("conf.yaml")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%#v", c)
}
Running instructions (in case it's the first time you step out of stdlib):
cat conf.yaml
go mod init example.com/whatever
go get gopkg.in/yaml.v3
cat go.sum
go run .
About The yaml:"field"
The tags (like yaml:"field") are optional for all-lowercase yaml key identifiers. For demonstration the above example parses an extra camel case identifier which does require such a tag.
Corner Case: JSON+YAML
Confusingly, the useful lowercasing behavior of yaml package is not seen in the standard json package. Do you have a data structure which is sometimes encoded to JSON and sometimes to YAML? If so, consider specifying both JSON tags and YAML tags on literally every field. Verbose, but reduces mistakes. Example below.
type myData struct {
Conf conf `yaml:"conf" json:"conf"`
}
type conf struct {
Hits int64 `yaml:"hits" json:"hits"`
Time int64 `yaml:"time" json:"time"`
CamelCase string `yaml:"camelCase" json:"camelCase"`
}
package main
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
)
type someConf struct {
AccessKeyID string `yaml:"access_key_id"`
//...
}
func getConf(file string, cnf interface{}) error {
yamlFile, err := ioutil.ReadFile(file)
if err == nil {
err = yaml.Unmarshal(yamlFile, cnf)
}
return err
}
func main() {
cfg := &awsConf{}
if err := getConf("conf.yml", cfg); err != nil {
log.Panicln(err)
}
}
shortest getConf ever

Resources