Created
December 15, 2015 13:52
-
-
Save 178inaba/13021c9c6ab673af7c4e to your computer and use it in GitHub Desktop.
gin render
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "net/http" | |
| "github.com/gin-gonic/gin" | |
| ) | |
| func main() { | |
| r := gin.Default() | |
| r.GET("/", renderJSON) | |
| r.Run(":8000") | |
| } | |
| func renderJSON(c *gin.Context) { | |
| ej := newErrJSON(gin.H{"message": "hey", "status": http.StatusOK}, "any error") | |
| c.Render(http.StatusOK, ej) | |
| } | |
| type errJSON struct { | |
| Data interface{} | |
| } | |
| func newErrJSON(data interface{}, errStr string) errJSON { | |
| return errJSON{Data: gin.H{"DATA": data, "ERROR": errStr}} | |
| } | |
| func (e errJSON) Render(w http.ResponseWriter) error { | |
| header := w.Header() | |
| if val := header["Content-Type"]; len(val) == 0 { | |
| header["Content-Type"] = []string{"application/json; charset=utf-8"} | |
| } | |
| return json.NewEncoder(w).Encode(e.Data) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment