2021-07-18 02:14:59 +02:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
2021-07-20 10:34:59 +02:00
|
|
|
// MIME type strings.
|
2021-07-18 02:14:59 +02:00
|
|
|
const (
|
|
|
|
ContentTypeJSON = "application/json"
|
2021-07-19 17:59:47 +02:00
|
|
|
ContentTypeJS = "application/javascript"
|
|
|
|
ContentTypeXML = "text/xml"
|
2021-07-18 02:14:59 +02:00
|
|
|
ContentTypeYAML = "text/yaml"
|
|
|
|
ContentTypeHTML = "text/html"
|
|
|
|
)
|
|
|
|
|
2021-07-19 17:59:47 +02:00
|
|
|
// Response sends an HTTP response.
|
|
|
|
//
|
|
|
|
// statusCode is the respone's status.
|
|
|
|
//
|
|
|
|
// If the request's Content-Type is JavaScript, JSON, YAML, or XML, it returns
|
|
|
|
// data serialized as JSONP, JSON, YAML, or XML, respectively. If the
|
|
|
|
// Content-Type is HTML, it returns the HTML template templateName rendered with
|
|
|
|
// data.
|
2021-07-18 02:14:59 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|