-
-
Save eufat/6fed61dd74f2188b231a8c2f137300db to your computer and use it in GitHub Desktop.
Simple JSON API Server in Go
This file contains hidden or 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" | |
"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