Skip to content

Commit

Permalink
simplify swagger
Browse files Browse the repository at this point in the history
  • Loading branch information
cszichao committed Mar 26, 2024
1 parent 7cb2667 commit f9b1b4e
Show file tree
Hide file tree
Showing 4 changed files with 150 additions and 2 deletions.
67 changes: 67 additions & 0 deletions generator/byte_var_writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package generator

import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"github.com/go-openapi/spec"

Check failure on line 8 in generator/byte_var_writer.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed (gofumpt)
"io"
"strings"

Check failure on line 10 in generator/byte_var_writer.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed (gofumpt)
)

type ByteVarWriter struct {
io.Writer
c int
}

func newByteVarWriter(w io.Writer) *ByteVarWriter {
return &ByteVarWriter{Writer: w}
}

func (w *ByteVarWriter) Write(p []byte) (n int, err error) {
if len(p) == 0 {
return
}

for n = range p {
if w.c%18 == 0 {
w.Writer.Write([]byte("\n"))

Check failure on line 29 in generator/byte_var_writer.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `w.Writer.Write` is not checked (errcheck)
}
fmt.Fprintf(w.Writer, "0x%02x,", p[n])
w.c++
}

n++

return
}

func encodeSwaggerToByteVar(v *spec.Swagger) (string, error) {
b := &strings.Builder{}
w := newByteVarWriter(b)
if err := encodeSwagger(v, w); err != nil {
return "", err
}
return b.String(), nil
}

func encodeSwagger(v *spec.Swagger, w io.Writer) error {
gzWriter := gzip.NewWriter(w)
encoder := json.NewEncoder(gzWriter)
err := encoder.Encode(v)

Check failure on line 52 in generator/byte_var_writer.go

View workflow job for this annotation

GitHub Actions / lint

ineffectual assignment to err (ineffassign)
if err = gzWriter.Flush(); err != nil {
return err
}
return gzWriter.Close()
}

func gzDecode(data []byte) ([]byte, error) {

Check failure on line 59 in generator/byte_var_writer.go

View workflow job for this annotation

GitHub Actions / lint

func `gzDecode` is unused (unused)
dataReader := bytes.NewReader(data)
gzReader, err := gzip.NewReader(dataReader)
if err != nil {
return nil, err
}
defer gzReader.Close()
return io.ReadAll(gzReader)
}
3 changes: 3 additions & 0 deletions generator/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,9 @@ type GenApp struct {
// generation option. Alternative methods to serve spec (e.g. from disk, ...) may be implemented by
// adding a middleware to the generated API.
FlatSwaggerJSON string

// bytes_var(gz(jsonEnc(simplify(FlatSwaggerJSON))))
SimplifySwagger string
ExcludeSpec bool
GenOpts *GenOpts
}
Expand Down
59 changes: 59 additions & 0 deletions generator/support.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"path"
"path/filepath"
"sort"
"strings"

"github.com/go-openapi/analysis"
"github.com/go-openapi/loads"
Expand Down Expand Up @@ -498,6 +499,11 @@ func (a *appGenerator) makeCodegenApp() (GenApp, error) {
jsonb, _ := json.MarshalIndent(a.SpecDoc.OrigSpec(), "", " ")
flatjsonb, _ := json.MarshalIndent(a.SpecDoc.Spec(), "", " ")

simplifySwaggerVar, err := encodeSwaggerToByteVar(a.SpecDoc.Spec())
if err != nil {
return GenApp{}, err
}

return GenApp{
GenCommon: GenCommon{
Copyright: a.GenOpts.Copyright,
Expand Down Expand Up @@ -530,13 +536,66 @@ func (a *appGenerator) makeCodegenApp() (GenApp, error) {
Principal: a.GenOpts.PrincipalAlias(),
SwaggerJSON: generateReadableSpec(jsonb),
FlatSwaggerJSON: generateReadableSpec(flatjsonb),
SimplifySwagger: simplifySwaggerVar,
ExcludeSpec: a.GenOpts.ExcludeSpec,
GenOpts: a.GenOpts,

PrincipalIsNullable: a.GenOpts.PrincipalIsNullable(),
}, nil
}

func simplifySwaggerSpec(s *spec.Swagger) *spec.Swagger {

Check failure on line 547 in generator/support.go

View workflow job for this annotation

GitHub Actions / lint

func `simplifySwaggerSpec` is unused (unused)
data, _ := json.Marshal(s)
ss := spec.Swagger{}
_ = json.Unmarshal(data, &ss)
p := make(map[string]spec.PathItem)
for swagPath, info := range ss.Paths.Paths {
if strings.HasPrefix(swagPath, "/-/") {
continue
}
for _, op := range []*spec.Operation{info.Get, info.Put,
info.Post, info.Delete, info.Options, info.Head, info.Patch} {
if op == nil {
continue
}
op.Description = ""
op.Summary = ""
op.Responses = &spec.Responses{
ResponsesProps: spec.ResponsesProps{
StatusCodeResponses: map[int]spec.Response{200: {
ResponseProps: spec.ResponseProps{Description: "OK"},
}},
},
}
parameters := make([]spec.Parameter, 0)
for _, parameter := range op.Parameters {
if parameter.Schema != nil {
parameter.Schema = &spec.Schema{}
}
parameter.Description = ""
parameter.Enum = nil
parameter.Example = nil
parameters = append(parameters, parameter)
}
op.Parameters = parameters
}
p[swagPath] = info

}
return &spec.Swagger{
SwaggerProps: spec.SwaggerProps{
Swagger: "2.0",
Info: ss.Info,
Consumes: ss.Consumes,
Produces: ss.Produces,
Schemes: ss.Schemes,
Paths: &spec.Paths{Paths: p},
SecurityDefinitions: ss.SecurityDefinitions,
Security: ss.Security,
},
}
}

// generateReadableSpec makes swagger json spec as a string instead of bytes
// the only character that needs to be escaped is '`' symbol, since it cannot be escaped in the GO string
// that is quoted as `string data`. The function doesn't care about the beginning or the ending of the
Expand Down
23 changes: 21 additions & 2 deletions generator/templates/swagger_json_embed.gotmpl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ package {{ .APIPackage }}
// Editing this file might prove futile when you re-run the swagger generate command

import (
"bytes"
"encoding/json"
"compress/gzip"
"log"
"io"

{{ imports .DefaultImports }}
{{ imports .Imports }}
Expand All @@ -25,6 +29,21 @@ var (
)

func init() {
SwaggerJSON = json.RawMessage([]byte(`{{ .SwaggerJSON }}`))
FlatSwaggerJSON = json.RawMessage([]byte(`{{ .FlatSwaggerJSON }}`))
var err error
if SwaggerJSON, err = gzDecode(swaggerJSONgz); err != nil {
log.Fatalln(err)
}
FlatSwaggerJSON = SwaggerJSON
}

func gzDecode(data []byte) ([]byte, error) {
dataReader := bytes.NewReader(data)
gzReader, err := gzip.NewReader(dataReader)
if err != nil {
return nil, err
}
defer gzReader.Close()
return io.ReadAll(gzReader)
}

var swaggerJSONgz = []byte{ {{ .SimplifySwagger }} }

0 comments on commit f9b1b4e

Please sign in to comment.