Skip to content

Instantly share code, notes, and snippets.

@dantheman213
Created September 26, 2017 22:38
Show Gist options
  • Select an option

  • Save dantheman213/169aef6340e744cb92e66170407f3501 to your computer and use it in GitHub Desktop.

Select an option

Save dantheman213/169aef6340e744cb92e66170407f3501 to your computer and use it in GitHub Desktop.
Simple Go Rest App
package main
import (
"fmt"
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
)
// The person Type (more like an object)
type Person struct {
Id string `json:"id,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Address *Address `json:"address,omitempty"`
}
type Address struct {
City string `json:"city,omitempty"`
State string `json:"state,omitempty"`
}
var people []Person
// Display all from the people var
func GetPeople(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(people)
}
// Display a single data
func GetPerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, item := range people {
if item.Id == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Person{})
}
// create a new item
func CreatePerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var person Person
_ = json.NewDecoder(r.Body).Decode(&person)
person.Id = params["id"]
people = append(people, person)
json.NewEncoder(w).Encode(people)
}
// Delete an item
func DeletePerson(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, item := range people {
if item.Id == params["id"] {
people = append(people[:index], people[index+1:]...)
break
}
json.NewEncoder(w).Encode(people)
}
}
// main function to boot up everything
func main() {
fmt.Println("Starting web server...")
router := mux.NewRouter()
fmt.Println("Loading data models...")
people = append(people, Person{Id: "1", FirstName: "Bob", LastName: "Rogers", Address: &Address{City: "Los Angeles", State: "CA"}})
people = append(people, Person{Id: "2", FirstName: "Ron", LastName: "Williams", Address: &Address{City: "Phoenix", State: "AZ"}})
fmt.Println("Loading routes...")
router.HandleFunc("/people", GetPeople).Methods("GET")
router.HandleFunc("/people/{id}", GetPerson).Methods("GET")
router.HandleFunc("/people/{id}", CreatePerson).Methods("POST")
router.HandleFunc("/people/{id}", DeletePerson).Methods("DELETE")
fmt.Println("Ready! Listening for requests...")
log.Fatal(http.ListenAndServe(":8000", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment