浏览代码

Merge pull request #8946 from unclejack/stream_decode

Decode JSON to avoid ReadFile
Alexandr Morozov 10 年之前
父节点
当前提交
b8678aa7f5
共有 3 个文件被更改,包括 18 次插入7 次删除
  1. 6 2
      daemon/container.go
  2. 7 3
      image/image.go
  3. 5 2
      volumes/volume.go

+ 6 - 2
daemon/container.go

@@ -102,13 +102,17 @@ func (container *Container) FromDisk() error {
 		return err
 	}
 
-	data, err := ioutil.ReadFile(pth)
+	jsonSource, err := os.Open(pth)
 	if err != nil {
 		return err
 	}
+	defer jsonSource.Close()
+
+	dec := json.NewDecoder(jsonSource)
+
 	// Load container settings
 	// udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it
-	if err := json.Unmarshal(data, container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") {
+	if err := dec.Decode(container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") {
 		return err
 	}
 

+ 7 - 3
image/image.go

@@ -38,14 +38,18 @@ type Image struct {
 }
 
 func LoadImage(root string) (*Image, error) {
-	// Load the json data
-	jsonData, err := ioutil.ReadFile(jsonPath(root))
+	// Open the JSON file to decode by streaming
+	jsonSource, err := os.Open(jsonPath(root))
 	if err != nil {
 		return nil, err
 	}
+	defer jsonSource.Close()
+
 	img := &Image{}
+	dec := json.NewDecoder(jsonSource)
 
-	if err := json.Unmarshal(jsonData, img); err != nil {
+	// Decode the JSON data
+	if err := dec.Decode(img); err != nil {
 		return nil, err
 	}
 	if err := utils.ValidateID(img.ID); err != nil {

+ 5 - 2
volumes/volume.go

@@ -154,12 +154,15 @@ func (v *Volume) FromDisk() error {
 		return err
 	}
 
-	data, err := ioutil.ReadFile(pth)
+	jsonSource, err := os.Open(pth)
 	if err != nil {
 		return err
 	}
+	defer jsonSource.Close()
 
-	return json.Unmarshal(data, v)
+	dec := json.NewDecoder(jsonSource)
+
+	return dec.Decode(v)
 }
 
 func (v *Volume) jsonPath() (string, error) {