Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add option to select custom struct tag for spec-generation #2806

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

fufuceng
Copy link

Hi All,

First, thanks for this library. It makes many things easier to implement.

I'm using go-swagger to generate swagger files from the code for almost 3 years. I've been searching for a way to provide custom names other than JSON tag and field name for a while. I thought that providing a custom struct tag while generating spec would be awesome.

Example:

Let's say I've struct like

type CreateUserRequest struct {
       XForwardedFor []string `json:"X-Forwarded-For" header:"X-Forwarded-For"`
       FirstName string `json:"firstName"`
}

I'm decoding the request according to the json, header, query tags. But I have to add the JSON tag to XForwardedFor field to show it in the swagger with the correct name. In this scenario, the client can override the XForwardedFor header by sending X-Forwarded-For field in the body. I think --struct-tag option can be useful in anyways.

Usage:
swagger generate spec -o ./docs/swagger.yaml --scan-models -w ./examples/generated --struct-tag swg

With --struct-tag swg struct will look like

type CreateUserRequest struct {
       XForwardedFor []string `header:"X-Forwarded-For" swg:"X-Forwarded-For"`
       FirstName string `json:"firstName" swg:"firstName"`
}

Signed-off-by: furkan fufuceng@gmail.com

@youyuanwu
Copy link
Member

Have you tried to modify/add tags in generated code using https://github.com/fatih/gomodifytags ?
I would do that instead of change the generator.

@casualjim
Copy link
Member

It would be good if the PR also included a fallback to the json tag, so look at custom tag first and then fall back to the json tag when it's not present, and perhaps allow for multiple alternative tags to be provided.

That way your use case can be addressed without adding extra swagger tags but rather look up in order: header, query, json for example.

Signed-off-by: furkan <fufuceng@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
generate spec Related to spec generation from code scanner
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants