Skip to content

Commit

Permalink
Feature: add examples for responses
Browse files Browse the repository at this point in the history
  • Loading branch information
UncleChair committed Oct 15, 2024
1 parent 12ea3a2 commit 846cd55
Showing 1 changed file with 17 additions and 43 deletions.
60 changes: 17 additions & 43 deletions net/goai/goai_path.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@
package goai

import (
"fmt"
"net/http"
"reflect"

"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/json"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gres"
"github.com/gogf/gf/v2/os/gstructs"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
Expand Down Expand Up @@ -280,12 +276,23 @@ func (oai *OpenApiV3) addPath(in addPathInput) error {
refInput.CommonResponseObject = nil
refInput.CommonResponseDataField = ""
}
responseExamplePath := outputMetaMap[gtag.ResponseExampleShort]
if responseExamplePath == "" {
responseExamplePath = outputMetaMap[gtag.ResponseExample]
}
examples := make(Examples)
if responseExamplePath != "" {
if err := examples.applyExamplesFile(responseExamplePath); err != nil {
return err
}
}
schemaRef, err := oai.getResponseSchemaRef(refInput)
if err != nil {
return err
}
response.Content[v] = MediaType{
Schema: schemaRef,
Schema: schemaRef,
Examples: examples,
}
}
operation.Responses[status] = ResponseRef{Value: &response}
Expand Down Expand Up @@ -354,47 +361,14 @@ func (oai *OpenApiV3) addPath(in addPathInput) error {
refInput.CommonResponseDataField = ""
}

examples := make(map[string]*ExampleRef)
responseExamplePath := gmeta.Get(outputObject.Interface(), gtag.ResponseExampleShort).String()
responseExamplePath := field.Tag(gtag.ResponseExampleShort)
if responseExamplePath == "" {
responseExamplePath = gmeta.Get(outputObject.Interface(), gtag.ResponseExample).String()
responseExamplePath = field.Tag(gtag.ResponseExample)
}
examples := make(Examples)
if responseExamplePath != "" {
var json string
if resource := gres.Get(responseExamplePath); resource != nil {
json = string(resource.Content())
} else {
absolutePath := gfile.RealPath(responseExamplePath)
if absolutePath != "" {
json = gfile.GetContents(absolutePath)
}
}
if json != "" {
var data interface{}
err := gjson.Unmarshal([]byte(json), &data)
if err != nil {
return err
}

switch v := data.(type) {
case map[string]interface{}:
for key, value := range v {
examples[key] = &ExampleRef{
Value: &Example{
Value: value,
},
}
}
case []interface{}:
for i, value := range v {
examples[fmt.Sprintf("example %d", i+1)] = &ExampleRef{
Value: &Example{
Value: value,
},
}
}
default:
}
if err := examples.applyExamplesFile(responseExamplePath); err != nil {
return err
}
}

Expand Down

0 comments on commit 846cd55

Please sign in to comment.