Use gorilla/mux

This commit is contained in:
Lena Fuhrimann 2016-12-20 19:47:36 +01:00
parent b822361b35
commit 7c0ca14525
6 changed files with 94 additions and 8 deletions

View file

@ -2,3 +2,5 @@ package: github.com/mastertinner/s3manager
import:
- package: github.com/minio/minio-go
version: ^2.0.2
- package: github.com/gorilla/mux
version: ^1.1.0

View file

@ -11,13 +11,13 @@ import (
minio "github.com/minio/minio-go"
)
// indexHandler forwards to "/buckets"
func indexHandler(w http.ResponseWriter, r *http.Request) {
// indexPageHandler forwards to "/buckets"
func indexPageHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/buckets", http.StatusPermanentRedirect)
}
// bucketsHandler handles the main page
func bucketsHandler(w http.ResponseWriter, r *http.Request) {
func bucketsPageHandler(w http.ResponseWriter, r *http.Request) {
lp := path.Join("templates", "layout.html")
ip := path.Join("templates", "index.html")
@ -38,7 +38,7 @@ func bucketsHandler(w http.ResponseWriter, r *http.Request) {
}
// bucketHandler handles the main page
func bucketHandler(w http.ResponseWriter, r *http.Request) {
func bucketPageHandler(w http.ResponseWriter, r *http.Request) {
bucket := strings.Split(r.URL.Path, "/")[2]
var objects []minio.ObjectInfo

24
logger.go Normal file
View file

@ -0,0 +1,24 @@
package main
import (
"log"
"net/http"
"time"
)
// Logger logs HTTP requests
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s\t%s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}

View file

@ -41,9 +41,7 @@ func main() {
panic(err)
}
http.HandleFunc("/", indexHandler)
http.HandleFunc("/buckets", bucketsHandler)
http.HandleFunc("/buckets/", bucketHandler)
router := NewRouter()
log.Fatal(http.ListenAndServe(":"+port, nil))
log.Fatal(http.ListenAndServe(":"+port, router))
}

27
router.go Normal file
View file

@ -0,0 +1,27 @@
package main
import (
"net/http"
"github.com/gorilla/mux"
)
// NewRouter creates a new router
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}

35
routes.go Normal file
View file

@ -0,0 +1,35 @@
package main
import "net/http"
// Route represents a path of the API
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
// Routes is an array of routes
type Routes []Route
var routes = Routes{
Route{
"Redirect to /buckets",
"GET",
"/",
indexPageHandler,
},
Route{
"Load Buckets Page",
"GET",
"/buckets",
bucketsPageHandler,
},
Route{
"Load Bucket Page",
"GET",
"/buckets/{bucketID}",
bucketPageHandler,
},
}