Skip to content

Instantly share code, notes, and snippets.

@AarynSmith
Last active May 2, 2018 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AarynSmith/1f22c55d9d9ca4085a5e3aa50d846034 to your computer and use it in GitHub Desktop.
Save AarynSmith/1f22c55d9d9ca4085a5e3aa50d846034 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")
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
}
p.ID = nextID
a.UserDB[nextID] = p
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment