Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | package swagger |
| 2 | |
| 3 | // Copyright 2015 Ernest Micklei. All rights reserved. |
| 4 | // Use of this source code is governed by a license |
| 5 | // that can be found in the LICENSE file. |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "encoding/json" |
| 10 | ) |
| 11 | |
| 12 | // ApiDeclarationList maintains an ordered list of ApiDeclaration. |
| 13 | type ApiDeclarationList struct { |
| 14 | List []ApiDeclaration |
| 15 | } |
| 16 | |
| 17 | // At returns the ApiDeclaration by its path unless absent, then ok is false |
| 18 | func (l *ApiDeclarationList) At(path string) (a ApiDeclaration, ok bool) { |
| 19 | for _, each := range l.List { |
| 20 | if each.ResourcePath == path { |
| 21 | return each, true |
| 22 | } |
| 23 | } |
| 24 | return a, false |
| 25 | } |
| 26 | |
| 27 | // Put adds or replaces a ApiDeclaration with this name |
| 28 | func (l *ApiDeclarationList) Put(path string, a ApiDeclaration) { |
| 29 | // maybe replace existing |
| 30 | for i, each := range l.List { |
| 31 | if each.ResourcePath == path { |
| 32 | // replace |
| 33 | l.List[i] = a |
| 34 | return |
| 35 | } |
| 36 | } |
| 37 | // add |
| 38 | l.List = append(l.List, a) |
| 39 | } |
| 40 | |
| 41 | // Do enumerates all the properties, each with its assigned name |
| 42 | func (l *ApiDeclarationList) Do(block func(path string, decl ApiDeclaration)) { |
| 43 | for _, each := range l.List { |
| 44 | block(each.ResourcePath, each) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // MarshalJSON writes the ModelPropertyList as if it was a map[string]ModelProperty |
| 49 | func (l ApiDeclarationList) MarshalJSON() ([]byte, error) { |
| 50 | var buf bytes.Buffer |
| 51 | encoder := json.NewEncoder(&buf) |
| 52 | buf.WriteString("{\n") |
| 53 | for i, each := range l.List { |
| 54 | buf.WriteString("\"") |
| 55 | buf.WriteString(each.ResourcePath) |
| 56 | buf.WriteString("\": ") |
| 57 | encoder.Encode(each) |
| 58 | if i < len(l.List)-1 { |
| 59 | buf.WriteString(",\n") |
| 60 | } |
| 61 | } |
| 62 | buf.WriteString("}") |
| 63 | return buf.Bytes(), nil |
| 64 | } |