2015-09-08 14:33:10 +03:00
package main
import (
"github.com/gorilla/mux"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/unrolled/render"
"fmt"
2015-09-09 01:22:34 +03:00
"io/ioutil"
"encoding/json"
"log"
2015-09-08 14:33:10 +03:00
)
var renderer = render . New ( )
type WebProvider struct {
Address string
}
type Page struct {
Configuration Configuration
}
func ( provider * WebProvider ) Provide ( configurationChan chan <- * Configuration ) {
systemRouter := mux . NewRouter ( )
2015-09-09 01:22:34 +03:00
systemRouter . Methods ( "GET" ) . PathPrefix ( "/web/" ) . Handler ( handlers . CombinedLoggingHandler ( os . Stdout , http . HandlerFunc ( GetHtmlConfigHandler ) ) )
systemRouter . Methods ( "GET" ) . PathPrefix ( "/api/" ) . Handler ( handlers . CombinedLoggingHandler ( os . Stdout , http . HandlerFunc ( GetConfigHandler ) ) )
systemRouter . Methods ( "POST" ) . PathPrefix ( "/api/" ) . Handler ( handlers . CombinedLoggingHandler ( os . Stdout , http . HandlerFunc (
func ( rw http . ResponseWriter , r * http . Request ) {
configuration := new ( Configuration )
b , _ := ioutil . ReadAll ( r . Body )
err := json . Unmarshal ( b , configuration )
2015-09-09 10:16:56 +03:00
if ( err == nil ) {
2015-09-09 01:22:34 +03:00
configurationChan <- configuration
2015-09-09 10:16:56 +03:00
GetConfigHandler ( rw , r )
2015-09-09 01:22:34 +03:00
} else {
2015-09-09 10:16:56 +03:00
log . Printf ( "Error parsing configuration %+v\n" , err )
http . Error ( rw , fmt . Sprintf ( "%+v" , err ) , http . StatusBadRequest )
2015-09-09 01:22:34 +03:00
}
} ) ) )
2015-09-08 14:33:10 +03:00
systemRouter . PathPrefix ( "/static/" ) . Handler ( http . StripPrefix ( "/static/" , http . FileServer ( http . Dir ( "static/" ) ) ) )
go http . ListenAndServe ( provider . Address , systemRouter )
}
func GetConfigHandler ( rw http . ResponseWriter , r * http . Request ) {
renderer . JSON ( rw , http . StatusOK , currentConfiguration )
}
func GetHtmlConfigHandler ( response http . ResponseWriter , request * http . Request ) {
2015-09-09 11:29:49 +03:00
renderer . HTML ( response , http . StatusOK , "configuration" , Page { Configuration : * currentConfiguration } )
2015-09-08 14:33:10 +03:00
}