Fieldnotes app backend

nomenclature_editor.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "github.com/dchest/safefile"
  7. "github.com/qri-io/jsonschema"
  8. )
  9. const nomenclatureSchemaPath = "schema/nomenclatures.json"
  10. func showNomenclatureEditorPage(w http.ResponseWriter, r *http.Request) {
  11. nomenclatures, err := ioutil.ReadFile(nomenclaturesPath)
  12. if err != nil {
  13. panic(err)
  14. }
  15. schema := getNomenclatureSchemaData()
  16. data := map[string]interface{}{
  17. "Nomenclatures": string(nomenclatures),
  18. "Schema": string(schema),
  19. }
  20. if err := xt.ExecuteTemplate(w, "nomenclature_editor.html.tmpl", data); err != nil {
  21. panic(err)
  22. }
  23. }
  24. func saveNomenclatures(w http.ResponseWriter, r *http.Request) {
  25. body, err := ioutil.ReadAll(r.Body)
  26. if err != nil {
  27. panic(err)
  28. }
  29. schema := getNomenclatureSchema()
  30. if errors, _ := schema.ValidateBytes(body); len(errors) > 0 {
  31. panic(errors)
  32. }
  33. f, err := safefile.Create(nomenclaturesPath, 0644)
  34. if err != nil {
  35. panic(err)
  36. }
  37. defer f.Close()
  38. if _, err := f.Write(body); err != nil {
  39. panic(err)
  40. }
  41. if err := f.Commit(); err != nil {
  42. panic(err)
  43. }
  44. w.WriteHeader(http.StatusNoContent)
  45. }
  46. func downloadNomenclatures(w http.ResponseWriter, r *http.Request) {
  47. http.ServeFile(w, r, nomenclaturesPath)
  48. }
  49. func getNomenclatureSchemaData() []byte {
  50. schema, err := ioutil.ReadFile(nomenclatureSchemaPath)
  51. if err != nil {
  52. panic(err)
  53. }
  54. return schema
  55. }
  56. func getNomenclatureSchema() *jsonschema.RootSchema {
  57. data := getNomenclatureSchemaData()
  58. rs := &jsonschema.RootSchema{}
  59. if err := json.Unmarshal(data, rs); err != nil {
  60. panic(err)
  61. }
  62. return rs
  63. }