Golang : HTTP response JSON encoded data
Alright, time to get dirty again.
I need to do a quick and easy http.Get()
from another server(let say server A) to retrieve some JSON encoded data. On server A, to fulfill request from the client, I need to write a simple Go program that serve JSON encoded data. Not entirely a RESTful API server, but nearly there.
Golang made it pretty easy to achieve this. The codes below demonstrate how to reply in JSON and to make this tutorial easy to understand. I've omitted couple of things like :
it is just to simulate a reply in JSON format based on given data in the URL's path.
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type JsonResponse map[string]interface{}
func (jr JsonResponse) String() (str string) { // add this method to print out String
byte, err := json.Marshal(jr)
if err != nil {
str = "" // return empty
return
}
str = string(byte) //ok,return cast byte to string
return
}
func JsonReplyAdam(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, JsonResponse{"name": "Adam", "age": 36, "job": "CEO", "success": true})
}
func JsonReplyEve(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, JsonResponse{"name": "Eve", "age": 30, "job": "CFO", "success": true})
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/adam", JsonReplyAdam)
mux.HandleFunc("/eve", JsonReplyEve)
http.ListenAndServe(":8080", mux)
}
Results :
URL : http://127.0.0.01:8080/eve
{"age":30,"job":"CFO","name":"Eve","success":true}
URL : http://127.0.0.01:8080/adam
{"age":36,"job":"CEO","name":"Adam","success":true}
References :
https://www.socketloop.com/tutorials/golang-process-json-data-with-jason-package
See also : Golang : Process json data with Jason package
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
+20.9k Golang : Encrypt and decrypt data with TripleDES
+17.5k Golang : Get all upper case or lower case characters from string example
+27.8k Golang : Change a file last modified date and time
+12.6k Golang : Convert(cast) uintptr to string example
+24k Golang : Time slice or date sort and reverse sort example
+9.2k Golang : ffmpeg with os/exec.Command() returns non-zero status
+6.3k Golang : Skip or discard items of non-interest when iterating example
+16k Golang : Convert slice to array
+6.4k Golang : How to setup a disk space used monitoring service with Telegram bot
+15.6k Golang : How to check if input from os.Args is integer?
+14k Golang : Reset buffer example
+7.7k Golang : Multiplexer with net/http and map