Is there a way to add an example for ref array model with go-swagger?
This problem is not really related to go-swagger, you just need to type and format your array into JSON to be compatible with go-swagger. One way to do this is to create a separate model definition for your MyArray
(and its schema - MyArraySchema
) and then reference it in your Myresponse
struct (and its schema - MyResponseSchema
). Like this (run in Playground):
// SO testing by JS
package main
import (
"encoding/json"
"fmt"
)
type MyArray struct {
Items []string `json:"items"`
}
type MyArraySchema struct { // Defining a schema for MyArray + example
Type string `json:"type"`
Items []string `json:"items"`
Example []string `json:"example"`
}
type MyResponse struct {
MyTestArray MyArray `json:"MyTestArray"`
}
type MyResponseSchema struct { // Define a schema for MyResponse + example
Type string `json:"type"`
Properties struct {
MyTestArray MyArraySchema `json:"MyTestArray"`
} `json:"properties"`
Example struct {
MyTestArray []string `json:"MyTestArray"`
} `json:"example"`
}
func main() {
// fmt.Println("Hello, Namaste!")
myArray := MyArray{
Items: []string{"Is", "This", "A", "Test", "Or", "Am", "I", "Serialized", "?"},
}
myResponse := MyResponse{
MyTestArray: myArray,
}
myResponseJSON, err := json.Marshal(myResponse)
if err != nil {
fmt.Println("Error marshaling MyResponse to JSON:", err)
return
}
fmt.Println(string(myResponseJSON))
}
The output of playground code:
{"MyTestArray":{"items":["Is","This","A","Test","Or","Am","I","Serialized","?"]}}
Program exited.