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

Q: Is there something like auto output detection? #2604

Open
TJM opened this issue Jan 5, 2021 · 1 comment
Open

Q: Is there something like auto output detection? #2604

TJM opened this issue Jan 5, 2021 · 1 comment

Comments

@TJM
Copy link

TJM commented Jan 5, 2021

Description

I like that gin-gonic can produce several different types of output, such as json, yaml, xml, html template, string, etc. I would like to "detect" what the user wants by looking at the "Accept" header, and run the appropriate c.WHATEVER based on that.

For example, if someone is querying via API they may ask for json output, but if they are using a browser, we should send them a rendered template (html).

Some items, like "serverListCSV" will still send CSV as a file, but I feel like it would be useful to have the same endpoints (routes) and controllers but just send the "display" portion to another method that would smartly format it.

Before I try to create this myself, can someone tell me if there is already something like this, and what it would be called (view controller is what comes to mind), where I would pass it the context, data and possibly a default type, and have it detect and send the appropriate type. I have tried googling various terms, related, but have just been led astray or maybe I just didn't understand the results.

@TJM
Copy link
Author

TJM commented Jan 6, 2021

I have found context.Negotiate, but couldn't find an example... I have something like:

var formatAllSupported = []string{gin.MIMEHTML, gin.MIMEJSON, gin.MIMEYAML, gin.MIMEPlain, gin.MIMEXML}

// GetAllPatchRun endpoint (GET)
func GetAllPatchRun(c *gin.Context) {
	data := gin.H{"status": "success", "patch_runs": models.GetPatchRuns()}
	c.Negotiate(http.StatusOK, gin.Negotiate{
		HTMLName: "run-list.gohtml",
		Data:     data,
		Offered:  formatAllSupported,
	})
}

... which is sorta kinda working. I think :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant