Created
May 15, 2018 12:28
example to encode/decode gob in gin https://github.com/gin-gonic/gin/issues/1357
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 ( | |
"bytes" | |
"encoding/gob" | |
"net/http" | |
"github.com/gin-gonic/gin" | |
) | |
type foobar interface { | |
Bar() string | |
} | |
type foo struct { | |
FooBar foobar `json:"foobar" binding:"required"` | |
} | |
// foofoo satisfies foobar interface | |
type foofoo struct { | |
BarBar string `json:"barbar"` | |
} | |
func (f *foofoo) Bar() string { return f.BarBar } | |
func init() { | |
// this is needed for gob encoding/decoding | |
gob.Register(&foofoo{}) | |
} | |
func main() { | |
r := gin.New() | |
r.GET("/json", func(c *gin.Context) { | |
ff := foofoo{BarBar: "bar string"} | |
f := foo{FooBar: &ff} | |
c.JSON(http.StatusOK, f) | |
}) | |
r.POST("/json-post", func(c *gin.Context) { | |
var f foo | |
// this should fail because Go cannot know the real type from JSON string. | |
if err := c.ShouldBindJSON(&f); err != nil { | |
errJSON(c, err) | |
return | |
} | |
c.JSON(http.StatusOK, f) | |
}) | |
r.GET("/gob", func(c *gin.Context) { | |
ff := foofoo{BarBar: "bar string"} | |
f := foo{FooBar: &ff} | |
out := bytes.NewBuffer(nil) | |
if err := gob.NewEncoder(out).Encode(&f); err != nil { | |
errJSON(c, err) | |
return | |
} | |
c.Data(http.StatusOK, "application/x-gob", out.Bytes()) | |
}) | |
r.POST("/gob-post", func(c *gin.Context) { | |
h, err := c.FormFile("file") | |
if err != nil { | |
errJSON(c, err) | |
return | |
} | |
file, err := h.Open() | |
if err != nil { | |
errJSON(c, err) | |
return | |
} | |
var f foo | |
if err := gob.NewDecoder(file).Decode(&f); err != nil { | |
errJSON(c, err) | |
return | |
} | |
c.JSON(http.StatusOK, f) | |
}) | |
r.Run(":8080") | |
} | |
func errJSON(c *gin.Context, err error) { | |
c.AbortWithStatusJSON( | |
http.StatusInternalServerError, | |
gin.H{"err": err.Error()}, | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment