1

I am trying to use go-swagger to generate my service swagger spec

I have a response struct like

type MyResponse struct {
    // example: ["This", "Is", "A", "Test"] 
    MyTestArray   MyArray `json:"MyTestArray"`
}

type MyArray []string

So, MyArray is just a typedef for []string, but when I try to use // example: the field, it is not working because MyArray is a ref model. When I use []string directly in the struct, it is working. Is there a way to add example for ref array model with go-swagger?

user1722361
  • 377
  • 1
  • 4
  • 14

1 Answers1

0

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.
Jishan Shaikh
  • 1,572
  • 2
  • 13
  • 31