-
-
Save primayudantra/52cd9306349b1bd3543dc90eb976ff94 to your computer and use it in GitHub Desktop.
Parsing JSON in a request body with Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
type Message struct { | |
Id int64 `json:"id"` | |
Name string `json:"name"` | |
} | |
// curl localhost:8000 -d '{"name":"Hello"}' | |
func Cleaner(w http.ResponseWriter, r *http.Request) { | |
// Read body | |
b, err := ioutil.ReadAll(r.Body) | |
defer r.Body.Close() | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
// Unmarshal | |
var msg Message | |
err = json.Unmarshal(b, &msg) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
output, err := json.Marshal(msg) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
w.Header().Set("content-type", "application/json") | |
w.Write(output) | |
} | |
func main() { | |
http.HandleFunc("/", Cleaner) | |
address := ":8000" | |
log.Println("Starting server on address", address) | |
err := http.ListenAndServe(address, nil) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment