You cannot select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
		
			
		
			
	
	
		
			58 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			Go
		
	
		
		
			
		
	
	
			58 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			Go
		
	
| 
											5 months ago
										 | package controller | ||
|  | 
 | ||
|  | import ( | ||
|  | 	"encoding/json" | ||
|  | 	"errors" | ||
|  | 	"io/ioutil" | ||
|  | 
 | ||
|  | 	"os" | ||
|  | 
 | ||
|  | 	"github.com/gin-gonic/gin" | ||
|  | 	log "github.com/sirupsen/logrus" | ||
|  | ) | ||
|  | 
 | ||
|  | var ( | ||
|  | 	// ErrJsonPayloadEmpty is returned when the JSON payload is empty.
 | ||
|  | 	ErrJsonPayloadEmpty = errors.New("JSON payload is empty") | ||
|  | ) | ||
|  | 
 | ||
|  | // DecodeJsonPayload reads the request body and decodes the JSON using json.Unmarshal.
 | ||
|  | func DecodeJsonPayload(c *gin.Context, v interface{}) error { | ||
|  | 
 | ||
|  | 	defer func() { | ||
|  | 		if r := recover(); r != nil { | ||
|  | 			log.Error("DecodeJsonPayload:", r) | ||
|  | 		} | ||
|  | 	}() | ||
|  | 
 | ||
|  | 	content, err := ioutil.ReadAll(c.Request.Body) | ||
|  | 	c.Request.Body.Close() | ||
|  | 	if err != nil { | ||
|  | 		return err | ||
|  | 	} | ||
|  | 	if len(content) == 0 { | ||
|  | 		return ErrJsonPayloadEmpty | ||
|  | 	} | ||
|  | 	err = json.Unmarshal(content, v) | ||
|  | 	if err != nil { | ||
|  | 		return err | ||
|  | 	} | ||
|  | 	return nil | ||
|  | } | ||
|  | 
 | ||
|  | func EncodeJsonPayload(v interface{}) (data interface{}, err error) { | ||
|  | 
 | ||
|  | 	defer func() { | ||
|  | 		if r := recover(); r != nil { | ||
|  | 			log.Error("EncodeJsonPayload:", r) | ||
|  | 		} | ||
|  | 	}() | ||
|  | 
 | ||
|  | 	obj_value, err := json.Marshal(v) | ||
|  | 	if err != nil { | ||
|  | 		log.Println("error:", err) | ||
|  | 	} | ||
|  | 	os.Stdout.Write(obj_value) | ||
|  | 	return obj_value, err | ||
|  | } |