1
0
Fork 0
confection/server.go

68 lines
1.3 KiB
Go
Raw Normal View History

2015-01-18 10:50:03 +00:00
package confection
import (
"encoding/json"
"fmt"
2015-01-19 11:23:04 +00:00
"io/ioutil"
2015-01-18 10:50:03 +00:00
"net/http"
"strconv"
2015-01-20 07:55:21 +00:00
"github.com/GeertJohan/go.rice"
2015-01-18 10:50:03 +00:00
)
type (
server struct {
2015-01-20 07:55:21 +00:00
manager *Manager
port int
staticHandler http.Handler
2015-01-18 10:50:03 +00:00
}
)
func (s *server) start() {
2015-01-20 07:55:21 +00:00
s.staticHandler = http.FileServer(rice.MustFindBox("static").HTTPBox())
2015-01-18 10:50:03 +00:00
portStr := ":" + strconv.Itoa(s.port)
fmt.Println("Configuration server is available at http://127.0.0.1" + portStr)
if err := http.ListenAndServe(portStr, s); err != nil {
panic(err)
}
}
func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
2015-01-20 07:55:21 +00:00
// Rewrite like a boss
if req.URL.Path == "/" {
req.URL.Path = "/config.html"
}
// Route like a boss
2015-01-19 11:23:04 +00:00
switch req.URL.Path {
2015-01-20 07:55:21 +00:00
case "/config.html", "/app.js", "/bootstrap.min.css":
s.staticHandler.ServeHTTP(w, req)
2015-01-19 11:23:04 +00:00
case "/fields.json":
s.fieldsHandler(w, req)
case "/save":
s.saveHandler(w, req)
default:
http.NotFound(w, req)
}
}
func (s *server) fieldsHandler(w http.ResponseWriter, req *http.Request) {
2015-01-18 10:50:03 +00:00
jsn, err := json.Marshal(s.manager.conf.meta(""))
if err != nil {
panic(err)
}
2015-01-19 11:23:04 +00:00
w.Header().Add("Content-Type", "application/json; charset=utf8")
2015-01-18 10:50:03 +00:00
w.Write(jsn)
}
2015-01-19 11:23:04 +00:00
func (s *server) saveHandler(w http.ResponseWriter, req *http.Request) {
b, err := ioutil.ReadAll(req.Body)
if err != nil {
panic(err)
}
s.manager.importJson(b)
}