Browse Source

Added support for general handlers in sleeply API registration.

Added CORS headers to stats API.
pull/3/head
Simon Eisenmann 12 years ago
parent
commit
1d0853ac93
  1. 25
      src/app/spreed-speakfreely-server/sleepy/core.go
  2. 20
      src/app/spreed-speakfreely-server/stats.go

25
src/app/spreed-speakfreely-server/sleepy/core.go

@ -42,6 +42,12 @@ type DeleteSupported interface { @@ -42,6 +42,12 @@ type DeleteSupported interface {
Delete(*http.Request) (int, interface{})
}
// HandleSupported is the interface that provides a general
// use method to support custom request processing.
type HandleSupported interface {
Handle(http.ResponseWriter, *http.Request) (int, []byte)
}
// An API manages a group of resources by routing requests
// to the correct method on a matching resource and marshalling
// the returned data to JSON for the HTTP response.
@ -59,7 +65,20 @@ func (api *API) requestHandler(resource interface{}) http.HandlerFunc { @@ -59,7 +65,20 @@ func (api *API) requestHandler(resource interface{}) http.HandlerFunc {
request.ParseForm()
var code int
var content []byte
var err error
if resource, ok := resource.(HandleSupported); ok {
var handle func(http.ResponseWriter, *http.Request) (int, []byte)
handle = resource.Handle
code, content = handle(rw, request)
} else {
var handler func(*http.Request) (int, interface{})
var data interface{}
switch request.Method {
case GET:
@ -85,15 +104,17 @@ func (api *API) requestHandler(resource interface{}) http.HandlerFunc { @@ -85,15 +104,17 @@ func (api *API) requestHandler(resource interface{}) http.HandlerFunc {
return
}
code, data := handler(request)
code, data = handler(request)
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
content, err := json.MarshalIndent(data, "", "\t")
content, err = json.MarshalIndent(data, "", "\t")
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
}
rw.WriteHeader(code)
rw.Write(content)
}

20
src/app/spreed-speakfreely-server/stats.go

@ -21,6 +21,7 @@ @@ -21,6 +21,7 @@
package main
import (
"encoding/json"
"net/http"
"runtime"
"time"
@ -71,12 +72,23 @@ type Stats struct { @@ -71,12 +72,23 @@ type Stats struct {
hub *Hub
}
func (stats *Stats) Get(r *http.Request) (int, interface{}) {
func (stats *Stats) Handle(rw http.ResponseWriter, r *http.Request) (int, []byte) {
if r.Method != "GET" {
return http.StatusMethodNotAllowed, nil
}
r.ParseForm()
details := r.FormValue("details") == "1"
stat := NewStat(details, stats.hub)
return 200, stat
data := NewStat(details, stats.hub)
rw.Header().Set("Access-Control-Allow-Origin", "*")
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
content, err := json.MarshalIndent(data, "", "\t")
if err != nil {
return http.StatusInternalServerError, nil
}
return 200, content
}

Loading…
Cancel
Save