Marshalling empty slice to empty JSON array instead of null in Go

You’d better don’t make them angry and make them happy giving them the proper `[]` empty array value. How to do that? Easily.

When you are creating the new slice like var people []Person you created new slice with you get the nil pointer to people var. And then there is a comprehensively a null value in output JSON. But if you create new slice with people := make([]Person, 0) you get the desired output. Or you can use people := []Person{}for same result too. See the whole code below or try it in playground. Tell me if the Frontend colleague invited you for a beer then.

In JSON APIs you often need to return array of data. In your Go code you probably use the slice []NameOfTheType to keep the list of the items. But when it comes to marshalling to JSON when the slice is empty you may get the JSON output contains null instead of an empty array. You should (but most of the time should not) see the faces of frontend developers when they face null instead of expected [] and try to iterate over it in JS 🙂


Continue Reading

TCP UDP request catcher

Very often during the software development I face the situation I need to log sent request fro my applications such as logs, metrics and so on. These request are in production directed to ELK stack, Prometheus, influxDB or to another 3rd party service. But for local development I don't want to run these services on my machine because of the resources consumption. I just want to verify if my app sent the data in proper format. Goreqbin is simple Go app that starts UDP and HTTP servers and logs all received requests. New servers and log methods may be easily added. Right now the output logging is to stdout only. It is good enough for me for development usage, but you are very welcome to contribute and and new output methods and/or new servers.

Continue Reading
Close Menu