Skip to content

Instantly share code, notes, and snippets.

@AarynSmith
Last active April 26, 2018 02:45
Show Gist options
  • Save AarynSmith/15cf2186d639ad0cf44afafa0591e40b to your computer and use it in GitHub Desktop.
Save AarynSmith/15cf2186d639ad0cf44afafa0591e40b to your computer and use it in GitHub Desktop.
package main
import (
"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)
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))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment