...

Source file src/github.com/go-openapi/validate/post/prune.go

Documentation: github.com/go-openapi/validate/post

     1  // Copyright 2018 go-swagger maintainers
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package post
    16  
    17  import (
    18  	"github.com/go-openapi/validate"
    19  )
    20  
    21  // Prune recursively removes all non-specified fields from the underlying data of the result.
    22  // The data must be a JSON struct as returned by json.Unmarshal.
    23  func Prune(r *validate.Result) {
    24  	prune(r.Data(), r)
    25  }
    26  
    27  func prune(data interface{}, result *validate.Result) {
    28  	switch obj := data.(type) {
    29  	case map[string]interface{}:
    30  		pruneObject(obj, result)
    31  		for _, val := range obj {
    32  			prune(val, result)
    33  		}
    34  	case []interface{}:
    35  		for _, item := range obj {
    36  			prune(item, result)
    37  		}
    38  	}
    39  }
    40  
    41  func pruneObject(obj map[string]interface{}, result *validate.Result) {
    42  	fieldSchemata := result.FieldSchemata()
    43  	for field := range obj {
    44  		if schemata, ok := fieldSchemata[validate.NewFieldKey(obj, field)]; !ok || len(schemata) == 0 {
    45  			delete(obj, field)
    46  		}
    47  	}
    48  }
    49  

View as plain text