Skip to content

Instantly share code, notes, and snippets.

@Noy
Last active May 22, 2017 10:04
Show Gist options
  • Save Noy/436463a490d4c0193cec373ee9210f63 to your computer and use it in GitHub Desktop.
Save Noy/436463a490d4c0193cec373ee9210f63 to your computer and use it in GitHub Desktop.
RESTful API Example
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
"encoding/json"
)
// Our person struct, (a collection of data representing a person
// Parsing the data as json, as a RESTful API example (omitempty - exclude if it's empty)
type Person struct {
// Their unique ID (to identify them easily)
ID string `json:"id,omitempty"`
// Their first name
FirstName string `json:"firstname,omitempty"`
// Their last name
LastName string `json:"lastname,omitempty"`
// Address...
Address *Address `json:"address,omitempty"`
}
// We want to store more information in the address, so we make a collection of data (struct) for that address
// Again json encoding
type Address struct {
// The city
City string `json:"city,omitempty"`
// The state
State string `json:"state,omitempty"`
}
// Creating our person slice - We will append to this
var people []Person
// Function to get each person, takes a ResponseWriter and a request (for our web server)
func GetPerson(w http.ResponseWriter, req *http.Request) {
// Create the parameters - from our server's variables
params := mux.Vars(req)
// Iterate through the range of people
for _, item := range people {
// Check if the ID matches our server's param id
if item.ID == params["id"] {
// Encode it
json.NewEncoder(w).Encode(item)
// stop
return
}
}
// Encode an empty person
json.NewEncoder(w).Encode(&Person{}) // null | empty person
}
func GetPeople(w http.ResponseWriter, req *http.Request) {
// This gets a person based on our 'people' slice
json.NewEncoder(w).Encode(people)
}
func CreatePerson(w http.ResponseWriter, req *http.Request) {
// Create the parameters - from our server's variables (again)
params := mux.Vars(req)
// Person variable
var person Person
// Decode the person
_ = json.NewDecoder(req.Body).Decode(&person)
// Set that id to our servers params
person.ID = params["id"]
// Append to the slice (add)
people = append(people, person)
// Encode the person (create it)
json.NewEncoder(w).Encode(people)
}
func DeletePerson(w http.ResponseWriter, req *http.Request) {
// Create the parameters - from our server's variables (again, again) lol
params := mux.Vars(req)
// Iterate through the people (with an index and an item)
for index, item := range people {
// we check if the id matches the server ID
if item.ID == params["id"] {
// Delete it from the slice and the server
people = append(people[:index], people[index+1:]...) // This is where the delete happens
break
}
}
// Encode that in json (so the server info updates)
json.NewEncoder(w).Encode(people)
}
// Main
func main() {
// Create our router mux
// The name mux stands for "HTTP request multiplexer".
// Like the standard http.ServeMux, mux.Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.
router := mux.NewRouter()
// Way of adding people, returns an array of people in json format
people = append(people, Person{
// Id
ID: "1",
// you get the point..
FirstName: "Owen",
LastName: "Raines",
Address: &Address{City: "LA", State: "CA"}})
people = append(people,
Person{ID: "2",
FirstName: "Keith",
LastName: "Altieri",
Address: &Address{City: "Honolulu", State:"HI"}})
people = append(people,
Person{
ID: "2",
FirstName: "Noy",
LastName: "H"})
// Handle each one of our functions that we made above which then parses it to our server
router.HandleFunc("/people", GetPeople).Methods("GET") // Get Request as we're getting data
router.HandleFunc("/people{id}", GetPerson).Methods("GET") // Get request as we're getting data
router.HandleFunc("/people{id}", CreatePerson).Methods("POST") // Post request as we're 'setting' data (creating)
router.HandleFunc("/people{id}", DeletePerson).Methods("DELETE") // Delete request as we're removing it
// Server the Web Server on port 12345 with our mux (router)
log.Fatal(http.ListenAndServe(":12345", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment