Skip to content

Instantly share code, notes, and snippets.

@briandowns
Created July 13, 2016 21:25
Show Gist options
  • Save briandowns/373bc7d2ac3d046d9b6530448098118d to your computer and use it in GitHub Desktop.
Save briandowns/373bc7d2ac3d046d9b6530448098118d to your computer and use it in GitHub Desktop.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"github.com/codegangsta/negroni"
"github.com/goincremental/negroni-sessions"
"github.com/goincremental/negroni-sessions/cookiestore"
"github.com/gorilla/mux"
"github.com/pborman/uuid"
"github.com/unrolled/render"
)
var signalsChan = make(chan os.Signal, 1)
func main() {
flag.Parse()
signal.Notify(signalsChan, os.Interrupt)
go func() {
for sig := range signalsChan {
log.Printf("Exiting... %v\n", sig)
signalsChan = nil
os.Exit(1)
}
}()
ren := render.New(render.Options{Layout: "layout"})
store := cookiestore.New([]byte(uuid.NewUUID().String()))
n := negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.NewStatic(http.Dir("public")),
)
n.Use(sessions.Sessions("session", store))
router := mux.NewRouter()
// Frontend
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, fmt.Sprintf("public/index.html"))
}).Methods("GET")
// simple get request to get a string box
router.HandleFunc("/api/v1/hello", func(w http.ResponseWriter, r *http.Request) {
ren.JSON(w, http.StatusOK, "hello")
}).Methods("GET")
// simple get with url field parameter
router.HandleFunc("/api/v1/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
ren.JSON(w, http.StatusOK, map[string]interface{}{"name": name})
}).Methods("GET")
n.UseHandler(router)
n.Run(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment