1// Copyright 2019 DeepMap, Inc. 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. 14package codegen 15 16import ( 17 "bufio" 18 "bytes" 19 "compress/gzip" 20 "encoding/base64" 21 "fmt" 22 "text/template" 23 24 "github.com/getkin/kin-openapi/openapi3" 25) 26 27// This generates a gzipped, base64 encoded JSON representation of the 28// swagger definition, which we embed inside the generated code. 29func GenerateInlinedSpec(t *template.Template, importMapping importMap, swagger *openapi3.T) (string, error) { 30 // Marshal to json 31 encoded, err := swagger.MarshalJSON() 32 if err != nil { 33 return "", fmt.Errorf("error marshaling swagger: %s", err) 34 } 35 36 // gzip 37 var buf bytes.Buffer 38 zw, err := gzip.NewWriterLevel(&buf, gzip.BestCompression) 39 if err != nil { 40 return "", fmt.Errorf("error creating gzip compressor: %s", err) 41 } 42 _, err = zw.Write(encoded) 43 if err != nil { 44 return "", fmt.Errorf("error gzipping swagger file: %s", err) 45 } 46 err = zw.Close() 47 if err != nil { 48 return "", fmt.Errorf("error gzipping swagger file: %s", err) 49 } 50 str := base64.StdEncoding.EncodeToString(buf.Bytes()) 51 52 var parts []string 53 const width = 80 54 55 // Chop up the string into an array of strings. 56 for len(str) > width { 57 part := str[0:width] 58 parts = append(parts, part) 59 str = str[width:] 60 } 61 if len(str) > 0 { 62 parts = append(parts, str) 63 } 64 65 // Generate inline code. 66 buf.Reset() 67 w := bufio.NewWriter(&buf) 68 err = t.ExecuteTemplate(w, "inline.tmpl", struct { 69 SpecParts []string 70 ImportMapping importMap 71 }{SpecParts: parts, ImportMapping: importMapping}) 72 if err != nil { 73 return "", fmt.Errorf("error generating inlined spec: %s", err) 74 } 75 err = w.Flush() 76 if err != nil { 77 return "", fmt.Errorf("error flushing output buffer for inlined spec: %s", err) 78 } 79 return buf.String(), nil 80} 81