Skip to content

Instantly share code, notes, and snippets.

@meatballhat
Last active May 17, 2016 15:36
Show Gist options
  • Save meatballhat/41cb0d3afc1234be95a72d4d0eb39f64 to your computer and use it in GitHub Desktop.
Save meatballhat/41cb0d3afc1234be95a72d4d0eb39f64 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
)
func StartHTTPS() {
r := mux.NewRouter().StrictSlash(false)
n := negroni.New()
n.UseHandler(r)
r.HandleFunc("/", Hello)
apiv1 := mux.NewRouter().PathPrefix("/api/v1/").Subrouter().StrictSlash(false)
apiv1.HandleFunc(`/groupinfo/{namespace}/{path:[a-zA-Z0-9-_\/]+}`, GroupInfo).Methods("GET")
apiv1.HandleFunc(`/groupinfo/{namespace}/{path:[a-zA-Z0-9-_\/]+}`, GroupInfo).Methods("POST")
r.PathPrefix("/api/v1/").Handler(negroni.New(
negroni.HandlerFunc(AtlasAuth),
negroni.Wrap(apiv1),
))
fmt.Println("Serving on :3001")
http.ListenAndServe(":3001", n)
}
func Hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there\n")
}
func AtlasAuth(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
vars := mux.Vars(r)
log.WithFields(log.Fields{
"vars": vars,
"request_addr": fmt.Sprintf("%p", r),
"handler": "AtlasAuth",
}).Info("mux vars for request")
if r.Method == "POST" {
if _, ok := vars["namespace"]; !ok {
log.Warn("namespace is empty can't continue")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "nope\n")
return
}
next(w, r)
}
next(w, r)
}
func GroupInfo(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
log.WithFields(log.Fields{
"vars": vars,
"request_addr": fmt.Sprintf("%p", req),
"handler": "GroupInfo",
}).Info("mux vars for request")
namespace := vars["namespace"]
path := vars["path"]
resp := fmt.Sprintf("{\"namespace\": %q, \"path\": %q}", namespace, path)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(resp))
}
func main() {
StartHTTPS()
}
Serving on :3001
time="2016-05-17T11:35:23-04:00" level=info msg="mux vars for request" handler=AtlasAuth request_addr=0xc8200d6000 vars=map[]
time="2016-05-17T11:35:23-04:00" level=info msg="mux vars for request" handler=GroupInfo request_addr=0xc8200d6000 vars=map[namespace:test path:a/b/c]
#!/usr/bin/env bash
exec curl -vvvv http://127.0.0.1:3001/api/v1/groupinfo/test/a/b/c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment