Search code examples
goswaggergo-swagger

Swagger parameter issue


Below is my code:

// swagger:route GET /user_list get_user
//
// Get a user profile
// Parameters:
//  user_id: userParam
// Consumes:
// - application/json
// Produces:
// - application/json
//
// Responses:
//      200: UserResponse

In my model for request I have added param like below:

// swagger:parameters userParam
type UserRequest struct {
    // aaaa
    // in: query
    UserId string `json:"user_id"`
}

I am getting below error when I generate swagger json.

panic: assignment to entry in nil map

goroutine 1 [running]:
github.com/go-swagger/go-swagger/scan.(*setOpParams).Parse(0xc428986a20, 0xc426439f30, 0x1, 0x1, 0x0, 0x0)
    /home/sotsys-056/go_10/src/github.com/go-swagger/go-swagger/scan/route_params.go:137 +0x635
github.com/go-swagger/go-swagger/scan.(*tagParser).Parse(0xc426e873d0, 0xc426439f30, 0x1, 0x1, 0x0, 0xc426439f30)
    /home/sotsys-056/go_10/src/github.com/go-swagger/go-swagger/scan/scanner.go:526 +0x52

When I remove parameters section it works fine I am not generate swagger json but with parameters I am not able to generate it.

I have also tried these ways too.

// Parameters:
//      - user_id: [in:query required:true type:string] Description goes her

parameters:
        - name: user_id
          in: query
          description: this argument is a string
          schema:
            type: string

Solution

  • Your example is incomplete. However, using what you have, your code should look something along the lines of this in its simplest form:

    // swagger:parameters GetUser
    type GetUser struct {
        // UserId that identifies a user.
        //
        // in: query
        UserId string `json:"user_id"`
    }
    
    // Returns a user.
    // swagger:response UserResponse
    type UserResponse struct { 
        // in: body
        Body struct {}
    }
    
    // swagger:route GET /user_list GetUser
    //
    // Get a user profile.
    //
    // Responses:
    //      200: UserResponse
    router.Get("/user_list", handler.GetUser)
    

    Notice how we have three things:

    1. The request object
    2. The response object
    3. The route that uses both the request and response object