1
0
Fork 0
secondly/server.go

63 lines
1.3 KiB
Go
Raw Normal View History

2015-08-29 13:56:19 +00:00
package secondly
import (
"encoding/json"
2015-08-29 16:34:30 +00:00
"io/ioutil"
2015-08-29 13:56:19 +00:00
"log"
"net/http"
2015-08-29 16:34:30 +00:00
"github.com/GeertJohan/go.rice"
2015-08-29 13:56:19 +00:00
)
func startServer(addr string) {
2015-08-29 16:34:30 +00:00
staticHandler := http.FileServer(rice.MustFindBox("static").HTTPBox())
2015-08-29 13:56:19 +00:00
mux := http.NewServeMux()
mux.HandleFunc("/fields.json", fieldsHandler)
2015-08-29 16:34:30 +00:00
mux.HandleFunc("/save", saveHandler)
// Static
mux.Handle("/app.js", staticHandler)
mux.Handle("/app.css", staticHandler)
mux.Handle("/config.html", staticHandler)
// Redirect from root to a static file. Ugly yet effective.
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/" {
http.Redirect(rw, req, "/config.html", http.StatusMovedPermanently)
}
})
2015-08-29 13:56:19 +00:00
log.Println("Starting configuration server on", addr)
go http.ListenAndServe(addr, mux)
}
func fieldsHandler(rw http.ResponseWriter, req *http.Request) {
fields := extractFields(config, "")
2015-08-29 16:34:30 +00:00
body, err := json.Marshal(fields)
if err != nil {
panic(err)
}
rw.Write(body)
}
func saveHandler(rw http.ResponseWriter, req *http.Request) {
cbody, err := ioutil.ReadAll(req.Body)
if err != nil {
panic(err)
}
updateConfig(cbody)
writeConfig()
resp := struct {
Success bool `json:"success"`
Msg string `json:"msg"`
}{
Success: true,
Msg: "Config successfully updated",
}
body, _ := json.Marshal(resp)
2015-08-29 13:56:19 +00:00
rw.Write(body)
}