If you want to round numbers in go, you have to implement it yourself, that is, until go 1.10 is released.
https://gist.github.com/e92b18a62f097e488cb29c83b0401723
Again, it's weird that go
lacks something as simple as a reverse string function. But there are times when you actually need it. Here's how you can do it:
https://gist.github.com/0b72edcffda642abcd8deba81aced0c6
Marshalling is the process of converting domain objects to a serialized format, such as json
. In order to write a golang
struct to a json
file, you need to marshal it first:
https://gist.github.com/752e524cf7dd853cd737c28e71c11fe5
If you set pretty
to true
, it will be saved in a more readable format. This is how our output json
will look like:
https://gist.github.com/f137435c84c1183f0b01d87c35c06791
Unmarshalling is the process of converting domain objects from a serialized format, such as json
. To load the json file to our golang
struct, we have to unmarshal the json
data:
https://gist.github.com/12ca8509a51e9d11b26460aa2daa0b2c
This is the json
file we are loading:
https://gist.github.com/2aef5a385e049fdd7e0228610a946393
In case you need to map golang map
to structs
, there is a library for it:
https://gist.github.com/f2a841b5bbb0f6d664d34477e22df3f7
There are times where you want to hide certain fields from the golang struct
before returning it as a json
response, but not with the json:"-"
approach. The example below shows how you remove the password field from the original struct:
https://gist.github.com/87d427a70a53eb25529def75ec43c559
When returning a json
response, you might want to return fields from other structs
, but want to avoid creating too many of them. One way to achieve this is by composition - you compose a new struct by embedding other structs
and you choose to exclude the fields too through shadowing (see previous example).
https://gist.github.com/d90b93715fb385a2ff05a1503b43c2be
The name of the fields returned in the json
is based on the json tag in your struct. You can overwrite them if you want your json
response to have different field name:
https://gist.github.com/f5ec87c3074f2efbd28180b10d92e9fc
It's probably wasn't that obvious, but concatenating array can be easily done as shown below:
https://gist.github.com/236f60df41b128eaaf648a3265e90ec1
Note that both arrays must be of the same type. Appending a string
array to an int
array will result in an error.
Here's a benchmark of a "hello world" request using wrk. View the full report below:
Language | No. Thread | No. Connection | Requests/sec | Latency |
---|---|---|---|---|
nodejs | 1 | 1 | 19606.26 | 53.87us |
go + stdlib | 1 | 1 | 19154.60 | 49.98us |
go + fasthttp | 1 | 1 | 27179.54 | 39.84us |
nodejs | 10 | 10 | 27627.49 | 360.79us |
go + stdlib | 10 | 10 | 52090.76 | 452.68us |
go + fasthttp | 10 | 10 | 77635.80 | 177.69us |
1 threads and 1 connections:
https://gist.github.com/6a7c2f461d40cdf865497a8fe190fc1f
Similar test carried out with 10 threads and 10 connections: