Skip to content

Instantly share code, notes, and snippets.

@dvwright
Last active September 2, 2023 18:53
Show Gist options
  • Save dvwright/4852fe63c753196fa077bb76928b4b20 to your computer and use it in GitHub Desktop.
Save dvwright/4852fe63c753196fa077bb76928b4b20 to your computer and use it in GitHub Desktop.
c.Request.Body is a stream, EOF after read from, example in Golang Gin
package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type SimpleUser struct {
Id int `json:"id"`
Email string `json:"email"`
Password string `json:"password"`
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Add("Access-Control-Allow-Origin", "*")
c.Writer.Header().Add("Content-Type", "application/json")
c.Next()
}
}
func handleErrors(c *gin.Context) {
c.Next()
errorToPrint := c.Errors.ByType(gin.ErrorTypePublic).Last()
if errorToPrint != nil {
c.JSON(500, gin.H{
"status": 500,
"message": errorToPrint.Error(),
})
}
}
func GetMainEngine() *gin.Engine {
r := gin.Default()
r.Use(handleErrors)
r.Use(Cors())
v1 := r.Group("api/v1")
{
v1.POST("/users", CreateUser)
}
v1.Use()
return r
}
func main() {
GetMainEngine().Run(":8080")
}
func OptionsDelPostPut(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Methods", "DELETE,POST, PUT")
//c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type")
c.Next()
}
func CreateUser(c *gin.Context) {
fmt.Println("Raw Request Body : %s", c.Request.Body)
var tuser SimpleUser
decoder := json.NewDecoder(c.Request.Body)
err := decoder.Decode(&tuser)
if err != nil {
fmt.Printf("error %s", err)
c.JSON(501, gin.H{"error": err})
}
//fmt.Printf("Decode Body %v\n\n", tuser)
fmt.Printf("Decoded Body Request Email : %v\n", tuser.Email)
fmt.Printf("Decoded Body Request Password : %v\n", tuser.Password)
var su SimpleUser
err = c.BindJSON(&su)
// err = Bind error EOF
// why not set?!
//fmt.Println("%v\n\n", su)
fmt.Printf("Bind Email - Why not Set? %v\n", su.Email)
fmt.Printf("Bind Password - Why not Set? %v\n", su.Password)
//email := c.PostForm("email") // not expected
//email = c.Params.ByName("email") // not expected
c.JSON(http.StatusCreated, gin.H{"success": "success"})
}
package main
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
)
func TestWhyNotBinding(t *testing.T) {
oParams := `{"email": "testEmail", "password": "testPassword"}`
req, _ := http.NewRequest("POST", "/api/v1/users", bytes.NewBufferString(oParams))
//req.Header.Add("Content-Type", "application/json; charset=UTF-8")
req.Header.Add("Content-Type", "application/json")
resp := httptest.NewRecorder()
ts := GetMainEngine()
ts.ServeHTTP(resp, req)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment