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
+8.2k Golang : How to check if input string is a word?
+6.9k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+18.5k Golang : Delete duplicate items from a slice/array
+6k Golang : How to search a list of records or data structures
+38.8k Golang : How to read CSV file
+18.9k Mac OSX : Homebrew and Golang
+5.8k Java : Human readable password generator
+32k Golang : Copy directory - including sub-directories and files
+11.3k Golang : Display a text file line by line with line number example
+18.6k Golang : How to make function callback or pass value from function as parameter?
+19.8k Golang : Check if os.Stdin input data is piped or from terminal
+7.3k Golang : Mapping Iban to Dunging alphabets