This commit is contained in:
Sander Hautvast 2016-02-24 17:17:58 +01:00
parent 8d76ed1f82
commit 67720f34cf
2 changed files with 14 additions and 1 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
/pkg
/src/fileserver/data
/src/github.com
/src/fileserver/public/node_modules/

View file

@ -6,8 +6,12 @@ import (
"log" "log"
"net/http" "net/http"
"strings" "strings"
"sync"
) )
var lock sync.Mutex
var port = ":8080"
func main() { func main() {
router := httprouter.New() router := httprouter.New()
router.GET("/dictionary/:dictionaryName", GetDictionary) router.GET("/dictionary/:dictionaryName", GetDictionary)
@ -16,7 +20,8 @@ func main() {
router.GET("/add/:dictionaryName/:key/:value", AddTranslation) router.GET("/add/:dictionaryName/:key/:value", AddTranslation)
router.NotFound = http.FileServer(http.Dir("public")) router.NotFound = http.FileServer(http.Dir("public"))
log.Fatal(http.ListenAndServe(":8080", router)) print("running on port", port)
log.Fatal(http.ListenAndServe(port, router))
} }
func GetDictionaries(res http.ResponseWriter, req *http.Request, _ httprouter.Params) { func GetDictionaries(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
@ -45,6 +50,8 @@ func GetDictionary(res http.ResponseWriter, req *http.Request, ps httprouter.Par
} }
func AddTranslation(res http.ResponseWriter, req *http.Request, ps httprouter.Params) { func AddTranslation(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
lock.Lock()
dictionary := ps.ByName("dictionaryName") dictionary := ps.ByName("dictionaryName")
data, err := ioutil.ReadFile("data/" + dictionary + ".json") data, err := ioutil.ReadFile("data/" + dictionary + ".json")
check(err) check(err)
@ -52,6 +59,8 @@ func AddTranslation(res http.ResponseWriter, req *http.Request, ps httprouter.Pa
addition := ",\n\"" + ps.ByName("key") + "\":\"" + ps.ByName("value") + "\"}" addition := ",\n\"" + ps.ByName("key") + "\":\"" + ps.ByName("value") + "\"}"
jsonText = strings.Replace(jsonText, "}", addition, 1) jsonText = strings.Replace(jsonText, "}", addition, 1)
ioutil.WriteFile("data/"+dictionary+".json", []byte(jsonText), 0644) ioutil.WriteFile("data/"+dictionary+".json", []byte(jsonText), 0644)
lock.Unlock()
} }
func NewDictionary(res http.ResponseWriter, req *http.Request, ps httprouter.Params) { func NewDictionary(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {