Skip to content

Instantly share code, notes, and snippets.

@AarynSmith
Last active May 2, 2018 02:11
Show Gist options
  • Save AarynSmith/2f09d3d2eace746e77e96c8f2ecf60c1 to your computer and use it in GitHub Desktop.
Save AarynSmith/2f09d3d2eace746e77e96c8f2ecf60c1 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type app struct {
Router *mux.Router
UserDB map[int]user
}
type user struct {
ID int
Name string
Role string
}
func main() {
a := app{}
a.Router = mux.NewRouter()
a.UserDB = map[int]user{
1: user{
ID: 1,
Name: "User 1",
Role: "Admin",
},
}
a.Run(":3001")
}
func (a *app) Run(addr string) (err error) {
log.Printf("Listening on %v", addr)
a.Router.HandleFunc("/user/{id:[0-9]+}", a.GetUser).Methods("GET")
a.Router.HandleFunc("/user", a.CreateUser).Methods("POST")
a.Router.HandleFunc("/user/{id:[0-9]+}", a.DeleteUser).Methods("DELETE")
a.Router.HandleFunc("/user/{id:[0-9]+}", a.ReplaceUser).Methods("PUT")
a.Router.HandleFunc("/user/{id:[0-9]+}", a.UpdateUser).Methods("PATCH")
return http.ListenAndServe(addr, a.Router)
}
func (a *app) GetUser(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id, err := strconv.Atoi(vars["id"])
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "500 Internal Server Error\n")
return
}
_, ok := a.UserDB[id]
if !ok {
w.WriteHeader(404)
fmt.Fprintf(w, "404 page not found\n")
return
}
j, err := json.Marshal(a.UserDB[id])
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "500 Internal Server Error\n")
return
}
fmt.Fprint(w, string(j))
}
func maxID(d map[int]user) (m int) {
for k := range d {
if k > m {
m = k
}
}
return m
}
func (a *app) CreateUser(w http.ResponseWriter, req *http.Request) {
nextID := maxID(a.UserDB) + 1
p := user{}
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
err := json.Unmarshal(buf.Bytes(), &p)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "500 Internal Server Error\n")
return
}
a.UserDB[nextID] = p
j, err := json.Marshal(a.UserDB[nextID])
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "500 Internal Server Error\n")
return
}
w.Header().Set("Location",
fmt.Sprintf("http://%s/user/%d", req.Host, nextID))
w.WriteHeader(200)
}
func (a *app) DeleteUser(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id, err := strconv.Atoi(vars["id"])
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "Could not delete user: %v", err.Error())
return
}
_, ok := a.UserDB[id]
if !ok {
w.WriteHeader(404)
fmt.Fprintf(w, "404 page not found\n")
return
}
delete(a.UserDB, id)
w.WriteHeader(200)
}
func (a *app) ReplaceUser(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id, err := strconv.Atoi(vars["id"])
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "Could not delete user: %v", err.Error())
return
}
p := user{}
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
err = json.Unmarshal(buf.Bytes(), &p)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "500 Internal Server Error\n")
return
}
_, ok := a.UserDB[id]
if !ok {
w.WriteHeader(404)
fmt.Fprintf(w, "404 page not found\n")
return
}
p.ID = id
a.UserDB[id] = p
w.WriteHeader(200)
}
func (a *app) UpdateUser(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id, err := strconv.Atoi(vars["id"])
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "Could not delete user: %v", err.Error())
return
}
pNew := user{}
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
err = json.Unmarshal(buf.Bytes(), &pNew)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "500 Internal Server Error\n")
return
}
_, ok := a.UserDB[id]
if !ok {
w.WriteHeader(404)
fmt.Fprintf(w, "404 page not found\n")
return
}
pNew.ID = id
if pNew.Name == "" {
pNew.Name = a.UserDB[id].Name
}
if pNew.Role == "" {
pNew.Role = a.UserDB[id].Role
}
a.UserDB[id] = pNew
w.WriteHeader(200)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment