Skip to content

Instantly share code, notes, and snippets.

@cbluth
Forked from tomnomnom/simple-json-api.go
Created July 13, 2019 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbluth/1cc35b9944b4faf40038c45f906667d5 to your computer and use it in GitHub Desktop.
Save cbluth/1cc35b9944b4faf40038c45f906667d5 to your computer and use it in GitHub Desktop.
Simple JSON API Server in Go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
// The `json:"whatever"` bit is a way to tell the JSON
// encoder and decoder to use those names instead of the
// capitalised names
type person struct {
Name string `json:"name"`
Age int `json:"age"`
}
var tom *person = &person{
Name: "Tom",
Age: 28,
}
func tomHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
// Just send out the JSON version of 'tom'
j, _ := json.Marshal(tom)
w.Write(j)
case "POST":
// Decode the JSON in the body and overwrite 'tom' with it
d := json.NewDecoder(r.Body)
p := &person{}
err := d.Decode(p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
tom = p
default:
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "I can't do that.")
}
}
func main() {
http.HandleFunc("/tom", tomHandler)
log.Println("Go!")
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment