소스 검색

Run JSON decoding through the usual setting of defaults and fixing up

I see no reason not to do this, and it gives a unified place (the prepare()
call) to initialize cached attributes and so on.
Jakob Borg 10 년 전
부모
커밋
9df701906f
2개의 변경된 파일17개의 추가작업 그리고 3개의 파일을 삭제
  1. 1 2
      cmd/syncthing/gui.go
  2. 16 1
      lib/config/config.go

+ 1 - 2
cmd/syncthing/gui.go

@@ -562,8 +562,7 @@ func (s *apiSvc) postSystemConfig(w http.ResponseWriter, r *http.Request) {
 	s.systemConfigMut.Lock()
 	s.systemConfigMut.Lock()
 	defer s.systemConfigMut.Unlock()
 	defer s.systemConfigMut.Unlock()
 
 
-	var to config.Configuration
-	err := json.NewDecoder(r.Body).Decode(&to)
+	to, err := config.ReadJSON(r.Body, myID)
 	if err != nil {
 	if err != nil {
 		l.Warnln("decoding posted config:", err)
 		l.Warnln("decoding posted config:", err)
 		http.Error(w, err.Error(), 500)
 		http.Error(w, err.Error(), 500)

+ 16 - 1
lib/config/config.go

@@ -8,6 +8,7 @@
 package config
 package config
 
 
 import (
 import (
+	"encoding/json"
 	"encoding/xml"
 	"encoding/xml"
 	"io"
 	"io"
 	"math/rand"
 	"math/rand"
@@ -83,6 +84,20 @@ func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
 	return cfg, err
 	return cfg, err
 }
 }
 
 
+func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
+	var cfg Configuration
+
+	setDefaults(&cfg)
+	setDefaults(&cfg.Options)
+	setDefaults(&cfg.GUI)
+
+	err := json.NewDecoder(r).Decode(&cfg)
+	cfg.OriginalVersion = cfg.Version
+
+	cfg.prepare(myID)
+	return cfg, err
+}
+
 type Configuration struct {
 type Configuration struct {
 	Version        int                   `xml:"version,attr" json:"version"`
 	Version        int                   `xml:"version,attr" json:"version"`
 	Folders        []FolderConfiguration `xml:"folder" json:"folders"`
 	Folders        []FolderConfiguration `xml:"folder" json:"folders"`
@@ -133,7 +148,7 @@ func (cfg *Configuration) WriteXML(w io.Writer) error {
 func (cfg *Configuration) prepare(myID protocol.DeviceID) {
 func (cfg *Configuration) prepare(myID protocol.DeviceID) {
 	fillNilSlices(&cfg.Options)
 	fillNilSlices(&cfg.Options)
 
 
-	// Initialize an empty slices
+	// Initialize any empty slices
 	if cfg.Folders == nil {
 	if cfg.Folders == nil {
 		cfg.Folders = []FolderConfiguration{}
 		cfg.Folders = []FolderConfiguration{}
 	}
 	}