From ffd77c3aab9f19dc3f4e4cc9e9b33dae5656cec7 Mon Sep 17 00:00:00 2001 From: Geno Date: Sun, 18 Jul 2021 02:14:59 +0200 Subject: [PATCH] web: response by content-type --- web/response.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 web/response.go diff --git a/web/response.go b/web/response.go new file mode 100644 index 0000000..7726fe3 --- /dev/null +++ b/web/response.go @@ -0,0 +1,42 @@ +package web + +import ( + "github.com/gin-gonic/gin" +) + +const ( + // ContentTypeJSON content type of json + ContentTypeJSON = "application/json" + // ContentTypeJS content type of javascript + ContentTypeJS = "application/javascript" + // ContentTypeXML content type of xml + ContentTypeXML = "text/xml" + // ContentTypeYAML content type of yaml + ContentTypeYAML = "text/yaml" + // ContentTypeHTML content type of html + ContentTypeHTML = "text/html" +) + +// Response give +func Response(ctx *gin.Context, statusCode int, data interface{}, templateName string) { + switch ctx.ContentType() { + case ContentTypeJS: + ctx.JSONP(statusCode, data) + return + case ContentTypeJSON: + ctx.JSON(statusCode, data) + return + case ContentTypeYAML: + ctx.YAML(statusCode, data) + return + case ContentTypeXML: + ctx.XML(statusCode, data) + return + case ContentTypeHTML: + ctx.HTML(statusCode, templateName, data) + return + default: + ctx.JSON(statusCode, data) + return + } +}