Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parsing JSON in a request body with Go
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)
}
}
@manoharreddyporeddy

This comment has been minimized.

Copy link

commented Jul 29, 2015

Great post!

@myangel26

This comment has been minimized.

Copy link

commented Nov 5, 2015

Thank

@ikrauchanka

This comment has been minimized.

Copy link

commented Apr 10, 2017

use decoder instead of unmarshal

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        var u User
        if r.Body == nil {
            http.Error(w, "Please send a request body", 400)
            return
        }
        err := json.NewDecoder(r.Body).Decode(&u)
        if err != nil {
            http.Error(w, err.Error(), 400)
            return
        }
        fmt.Println(u.Id)
    })
    log.Fatal(http.ListenAndServe(":8080", nil))
}
@rb16

This comment has been minimized.

Copy link

commented Jul 11, 2017

Yes you are right @ikrauchanka

@casoetan

This comment has been minimized.

Copy link

commented Nov 19, 2017

thanks @ikrauchanka & @aodin

@kwiesmueller

This comment has been minimized.

Copy link

commented Sep 13, 2018

@eoconnor

This comment has been minimized.

Copy link

commented Nov 15, 2018

@kwiesmueller: If you look at that blog post you linked, it mentions that the issue in question was addressed in Go 1.7.

@CelesteComet

This comment has been minimized.

Copy link

commented Jan 25, 2019

If you use decoder, the server won't care if you are sending invalid json strings that don't match your interface

@tzachshabtay

This comment has been minimized.

Copy link

commented Jan 30, 2019

@eoconnor I read the blog post: the third issue was fixed, but the first 2 points in the blog post still seem valid.

Also, unrelated, but r.Body.Close() might return an error but it's ignored in the gist.

@Lweiis

This comment has been minimized.

Copy link

commented Aug 30, 2019

Thx!!! This helped me a lot~😊

@FridaKemp

This comment has been minimized.

Copy link

commented Sep 6, 2019

So helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.