golang-lib/web/response.go

46 lines
1.0 KiB
Go
Raw Normal View History

2021-07-18 02:14:59 +02:00
package web
import (
"github.com/gin-gonic/gin"
)
// 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
}
}