Skip to content

Instantly share code, notes, and snippets.

@math-alpha
Created April 5, 2019 00:35
Show Gist options
  • Save math-alpha/eb23184ba2e5076feba8183ca4b424f0 to your computer and use it in GitHub Desktop.
Save math-alpha/eb23184ba2e5076feba8183ca4b424f0 to your computer and use it in GitHub Desktop.
Small restful api in go followed from the this (tutorial)[https://www.codementor.io/codehakase/building-a-restful-api-with-golang-a6yivzqdo]
package main
import (
"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"`
Country 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) // appending all the data in the response
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() {
router := mux.NewRouter()
people = append(people, Person{ID: "1", Firstname: "Yopa", Lastname: "Hubert", Address: &Address{City: "Bangangte", State: "West", Country: "Cameroon"}})
people = append(people, Person{ID: "2", Firstname: "Ngadou", Lastname: "Yopa", Address: &Address{City: "Buea", State: "South west", Country: "Cameroon"}})
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")
log.Fatal(http.ListenAndServe(":8000", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment