Golang : Output or print out JSON stream/encoded data
Problem :
You need to produce JSON stream or JSON encoded data to web browser or client. How to do that?
Solution :
Set the header Content-Type
to application/json
and write the http.ResponseWriter.
For example :
package main
import (
"net/http"
)
func Employees(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// NOTE : put jsonStr in a FOR loop to read forever from database and encode the data with
// json.Marshal() function to produce JSON stream
// see https://www.socketloop.com/tutorials/golang-convert-csv-data-to-json-format-and-save-to-file
// for this example, we will use static JSON string
jsonStr := `[{"Name":"Dennis","Age":16,"Job":"CEO"},
{"Name":"Eva","Age":34,"Job":"CFO"},
{"Name":"Paul","Age":28,"Job":"COO"}]`
// output to web or client
w.Write([]byte(jsonStr))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", Employees)
http.ListenAndServe(":8080", mux)
}
Reference :
https://www.socketloop.com/tutorials/golang-unmarshal-json-from-http-response
See also : Golang : Unmarshal JSON from http response
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+25.5k Golang : How to read integer value from standard input ?
+17.9k Golang : Get command line arguments
+10.4k Golang : Underscore string example
+6.3k Golang : Map within a map example
+7.6k Golang : Getting Echo framework StartAutoTLS to work
+23.7k Golang : Upload to S3 with official aws-sdk-go package
+30.1k Golang : How to redirect to new page with net/http?
+28.7k Golang : Get first few and last few characters from string
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.
+12.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+11.2k Golang : Generate DSA private, public key and PEM files example
+6.6k Mac/Linux/Windows : Get CPU information from command line