Add static page routing, place API under /api/

This commit is contained in:
nemunaire 2016-01-13 01:22:01 +01:00
parent e89af34c5c
commit d635420a9f
3 changed files with 29 additions and 9 deletions

View file

@ -11,18 +11,24 @@ import (
type DispatchFunction func([]string, []byte) (interface{}, error) type DispatchFunction func([]string, []byte) (interface{}, error)
var apiRouting = map[string]*(map[string]DispatchFunction){ var apiRoutes = map[string]*(map[string]DispatchFunction){
"version": &ApiVersionRouting, "version": &ApiVersionRouting,
"themes": &ApiThemesRouting, "themes": &ApiThemesRouting,
"teams": &ApiTeamsRouting, "teams": &ApiTeamsRouting,
} }
func ApiRouting(w http.ResponseWriter, r *http.Request) { type apiRouting struct{}
func ApiHandler() http.Handler {
return apiRouting{}
}
func (a apiRouting) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("Handling %s request from %s: %s [%s]\n", r.Method, r.RemoteAddr, r.URL.Path, r.UserAgent()) log.Printf("Handling %s request from %s: %s [%s]\n", r.Method, r.RemoteAddr, r.URL.Path, r.UserAgent())
// Extract URL arguments // Extract URL arguments
var sURL = strings.Split(r.URL.Path, "/") var sURL = strings.Split(r.URL.Path, "/")[1:]
if sURL[len(sURL)-1] == "" && len(sURL) > 2 { if len(sURL) > 1 && sURL[len(sURL)-1] == "" {
// Remove trailing / // Remove trailing /
sURL = sURL[:len(sURL)-1] sURL = sURL[:len(sURL)-1]
} }
@ -52,12 +58,12 @@ func ApiRouting(w http.ResponseWriter, r *http.Request) {
} }
// Route request // Route request
if len(sURL) > 1 { if len(sURL) > 0 {
if h, ok := apiRouting[sURL[1]]; ok { if h, ok := apiRoutes[sURL[0]]; ok {
if f, ok := (*h)[r.Method]; ok { if f, ok := (*h)[r.Method]; ok {
ret, err = f(sURL[2:], body) ret, err = f(sURL[1:], body)
} else { } else {
err = errors.New(fmt.Sprintf("Invalid action (%s) provided for %s.", r.Method, sURL[1])) err = errors.New(fmt.Sprintf("Invalid action (%s) provided for %s.", r.Method, sURL[0]))
} }
} }
} else { } else {

View file

@ -34,7 +34,12 @@ func main() {
} }
log.Println("Registering handlers...") log.Println("Registering handlers...")
http.HandleFunc("/", ApiRouting) mux := http.NewServeMux()
mux.Handle("/api/", http.StripPrefix("/api", ApiHandler()))
mux.HandleFunc("/teams", StaticRouting)
mux.HandleFunc("/themes", StaticRouting)
mux.Handle("/", http.FileServer(http.Dir("./static/")))
http.HandleFunc("/", mux.ServeHTTP)
log.Println(fmt.Sprintf("Ready, listening on %s", *bind)) log.Println(fmt.Sprintf("Ready, listening on %s", *bind))
if err := http.ListenAndServe(*bind, nil); err != nil { if err := http.ListenAndServe(*bind, nil); err != nil {

9
admin/static.go Normal file
View file

@ -0,0 +1,9 @@
package main
import (
"net/http"
)
func StaticRouting(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
}