Request JSON

Untuk request json bisa digunakan method ShouldBind seperti code dibawah ini

package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.POST("/", PostJSON)
	r.Run(":5000")
}

type User struct {
	Username string
	Password string
}

func PostJSON(ctx *gin.Context) {
	var user User
	if err := ctx.ShouldBind(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  http.StatusBadRequest,
			"message": err,
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"status": 	http.StatusOK,
			"data":		map[string]interface{}{
				"username": user.Username,
				"password": user.Password,	
			},
		})
	}
}

Untuk request dengan tipe array JSON perlu tipe data slice sebagai penampungnya.

package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.POST("/", PostJSON)
	r.Run(":5000")
}

type User struct {
	Username string
	Password string
}

func PostJSON(ctx *gin.Context) {
	var user []User
	if err := ctx.ShouldBind(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"status":  http.StatusBadRequest,
			"message": err,
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"status": 	http.StatusOK,
			"data":		user,
		})
	}
}

Last updated