traefik/web.go

62 lines
2 KiB
Go
Raw Normal View History

2015-09-08 11:33:10 +00:00
package main
import (
"github.com/gorilla/mux"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/unrolled/render"
"fmt"
"html/template"
2015-09-08 22:22:34 +00:00
"io/ioutil"
"encoding/json"
"log"
"reflect"
2015-09-08 11:33:10 +00: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-08 22:22:34 +00: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)
log.Println(err)
if (err!= nil && reflect.DeepEqual(new(Configuration), configuration)) {
configurationChan <- configuration
renderer.JSON(rw, http.StatusCreated, map[string]string{"result": "OK"})
}else{
renderer.JSON(rw, http.StatusBadRequest, map[string]string{"result": "error"})
}
})))
2015-09-08 11:33:10 +00: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) {
templates := template.Must(template.ParseFiles("configuration.html"))
response.Header().Set("Content-type", "text/html")
err := request.ParseForm()
if err != nil {
http.Error(response, fmt.Sprintf("error parsing url %v", err), 500)
}
2015-09-08 20:57:27 +00:00
templates.ExecuteTemplate(response, "configuration.html", Page{Configuration:*currentConfiguration})
2015-09-08 11:33:10 +00:00
}