Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created March 30, 2015 16:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save joyrexus/bc2ab8815cd278d42171 to your computer and use it in GitHub Desktop.
parse JSON request

Simple demo of how to decode JSON data coming from an http POST request.

Run the server with go run server.go and then make a curl request:

. post.sh

... or ...

curl -d @- http://localhost:8080/user
{
  "name": {
    "first": "Bob",
    "last":  "Jones"
  }
}
# CTRL-D

You should get back:

Hi Bob Jones!

For more about JSON and Go, see this blog post, or this example code.

#!/bin/sh
curl -d '{"name": {"first": "Bob", "last": "Jones"}}' http://localhost:8080/user
package main
import (
"fmt"
"net/http"
"encoding/json"
)
type Person struct {
Name struct {
First string `json:"first"`
Last string `json:"last"`
} `json:"name"`
}
func parse(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
var p Person
err := dec.Decode(&p)
if err != nil {
panic(err)
}
fmt.Fprintf(w, "Hi %s %s!\n", p.Name.First, p.Name.Last)
}
func main() {
http.HandleFunc("/user", parse)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment