1

I've got a Go project, exposing REST CRUD APIs, for a Mongo collection. I'm using go-swagger to generate the swagger spec. However, I'm having trouble getting the JSON response to look like I want without breaking the go-swagger spec generator.

I'm trying to use go-swagger to generate a swagger-spec from annotations on go code. I'd like to see if I can make the response just be a JSON Array of Users, like below.

Is there a way to adjust the json annotation on the User struct to produce the desired result?

[
    {"id": "5d8e9aaca00ef6123c989f69", "user_name": "zbeeblebrox"}, 
    {"id": "5d8e9ab1a00ef6123c989f6a", "user_name": "another_user"}
]

Below is what I'm getting, understandably, a JSON object, containing key "data", with a value of an Array of User objects.

I've tried redefining the swagger response struct to be an alias of type []*User, which creates the right response body, but it breaks the go swagger generator.

{
  "data": [
    {"id": "5d8e9aaca00ef6123c989f69", "user_name": "zbeeblebrox"}, 
    {"id": "5d8e9ab1a00ef6123c989f6a", "user_name": "another_user"}
  ]
}

Here's some code.

// swagger:model
type User struct {
    Id             *primitive.ObjectID      `json:"id,omitempty" bson:"_id,omitempty"`
    UserName       string                   `json:"user_name" bson:"user_name"`
}

// HTTP status code 200 and an array of repository models in data
//swagger:response usersResp
type swaggUsersResp struct {
    // in:body
    Data []*User `json:"data"`
}

I also tried doing it as an alias, which provides the desired JSON response, but breaks Go-Swagger code generation. I suspect this is because the swagger:response annotation is expected to be on a struct, not an alias.

// swagger:response usersResp
type swaggUsersResp = []*User
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
dbh
  • 1,607
  • 13
  • 18
  • I have the exact same situation producing the desired result, with the difference that the json tag for the body is `json:"body"` – Burak Serdar Sep 28 '19 at 05:50

0 Answers0