Tag: go

json: cannot unmarshal object into Go struct field

Problem json: cannot unmarshal object into Go struct field Code package main import ( “encoding/json” “fmt” ) // DTO object type mould struct { Particle tiny } type tiny interface { GetName() string } // Implement the interface type speck struct { Name string `json:”name”` } func (s *speck) GetName() string { return s.Name }…

HTTP Request Body for Form Values

HTTP Request Header HTTP clients and servers largely depend on the “Content-Type” header to determine how to parse the request/response body. Common values for the “Content-Type” header are application/json application/atom+xml application/pdf application/octet-stream application/x-www-form-urlencoded and request/response body should be processed as JSON, XML, PDF, Raw Stream, or Form Data respectively. How is Form Data Sent? 99.99%…

Why be careful with defer in Golang

When does defer function executes? The standard answer is: defer runs a function before the enclosing function returns. It is a wrong explanation. The defer executes as follows: The enclosing function has processed returned values and stored them in registers All defer functions run in a LIFO order of definition. If the return parameters are…

Time Complexity of a Memoized Algorithm

The memoization eliminated duplicate calls to a function. A memoized implementation of Fibonacci code is as follows: package complexity import “fmt” var mem map[int]int func fibo(count int) int { if count == 0 || count == 1 { return count } if mem[count] != -1 { return mem[count] } s := fibo(count-1) + fibo(count-2) mem[count]…

Summary: How to Write Go Code

Summary: How to Write Go Code The code organization follows repository -> module -> packages. Use go mod init and initialize module root as desired e.g. example.com/user/hello The Go binary goes to the path set in GOBIN All imported modules are stored in GOPATH/pkg/mod subdirectory The command go clean -modcache cleans downloaded packages. Reference https://golang.org/doc/code.html…

Go, gorm, nested JSON and associations

Go, gorm, nested JSON and associations gorm provides a clean way to store a nested JSON with the relation of associations among tables. The following code creates a DB with three levels of nesting. package main import ( “encoding/json” “fmt” “github.com/jinzhu/gorm” _ “github.com/lib/pq” ) const ( host = “localhost” port = 5432 user = “postgres”…

go tool: no such tool “compile”

I started facing go tool: no such tool “compile” error after installing a local build of go. The golang source was in /usr/local $ cd /usr/local $ ls total 41240 drwxr-xr-x@ 19 root wheel 608B Oct 18 19:35 go drwxr-xr-x 16 root wheel 512B Oct 18 19:35 . -rw-r–r–@ 1 root wheel 20M Oct 18…