Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created January 20, 2019 23:17
Show Gist options
  • Save fearofcode/f9b38f6002fe03992e415675bee67ce6 to your computer and use it in GitHub Desktop.
Save fearofcode/f9b38f6002fe03992e415675bee67ce6 to your computer and use it in GitHub Desktop.
simple usage of Gorilla Mux in Go
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
// Note is a note
type Note struct {
ID int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
CreatedOn time.Time `json:"created_on"`
}
var noteStore = make(map[int]Note)
var id int
// PostNoteHandler creates a note
func PostNoteHandler(w http.ResponseWriter, r *http.Request) {
var note Note
err := json.NewDecoder(r.Body).Decode(&note)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
note.ID = id
note.CreatedOn = time.Now()
noteStore[id] = note
id++
j, err := json.Marshal(note)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write(j)
}
// GetNotesHandler gets all notes
func GetNotesHandler(w http.ResponseWriter, r *http.Request) {
notes := make([]Note, 0)
for _, v := range noteStore {
notes = append(notes, v)
}
w.Header().Set("Content-Type", "application/json")
j, err := json.Marshal(notes)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write(j)
}
// GetNoteHandler gets a single note
func GetNoteHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
if note, ok := noteStore[id]; ok {
w.Header().Set("Content-Type", "application/json")
serializedNote, err := json.Marshal(note)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write(serializedNote)
} else {
w.Write([]byte("Not found"))
w.WriteHeader(http.StatusNotFound)
return
}
}
func main() {
note := Note{
Title: "test title",
Description: "test description",
CreatedOn: time.Now(),
ID: id,
}
noteStore[0] = note
id++
r := mux.NewRouter().StrictSlash(false)
r.HandleFunc("/api/notes", GetNotesHandler).Methods("GET")
r.HandleFunc("/api/notes/", GetNotesHandler).Methods("GET")
r.HandleFunc("/api/notes/{id}", GetNoteHandler).Methods("GET")
r.HandleFunc("/api/notes", PostNoteHandler).Methods("POST")
r.HandleFunc("/api/notes/", PostNoteHandler).Methods("POST")
server := &http.Server{
Addr: ":8080",
Handler: r,
}
log.Println(">> Listening on :8080")
server.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment