https://blog.logrocket.com/gin-binding-in-go-a-tutorial-with-examples/
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type Body struct {
// json tag to de-serialize json body
Name string `json:"name"`
}
func main() {
engine:=gin.New()
engine.POST("/test", func(context *gin.Context) {
body:=Body{}
// using BindJson method to serialize body with struct
if err:=context.BindJSON(&body);err!=nil{
context.AbortWithError(http.StatusBadRequest,err)
return
}
fmt.Println(body)
context.JSON(http.StatusAccepted,&body)
})
engine.Run(":3000")
}
setup
go mod init github.com/Crashlaker/test
go get -u github.com/gin-gonic/gin@latest
GoLang : Dynamic JSON Parsing using empty Interface and without Struct in Go Language
https://irshadhasmat.medium.com/golang-simple-json-parsing-using-empty-interface-and-without-struct-in-go-language-e56d0e69968
===
attempt
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
type Body struct {
// json tag to de-serialize json body
Name string `json:"name"`
}
func main() {
engine := gin.New()
engine.GET("/users", func(c *gin.Context) {
page := c.Query("page")
fmt.Println("page", page)
content, err := ioutil.ReadFile("users.json")
if err != nil {
log.Fatal(err)
}
var users []map[string]interface{}
json.Unmarshal([]byte(content), &users)
var filtered []map[string]interface{}
for _, user := range users {
if strings.Contains(user["name"].(string), "yuan") {
filtered = append(filtered, user)
}
}
c.JSON(http.StatusOK, &filtered)
})
engine.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
engine.POST("/test", func(context *gin.Context) {
body := Body{}
// using BindJson method to serialize body with struct
if err := context.BindJSON(&body); err != nil {
context.AbortWithError(http.StatusBadRequest, err)
return
}
fmt.Println(body)
context.JSON(http.StatusAccepted, &body)
})
engine.Run(":3000")
}