base_controller.go 1.1 KB
package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/web/beego/utils"
)

type BaseController struct {
	beego.Controller
}

func (controller BaseController) JsonUnmarshal(v interface{}) error {
	body := controller.Ctx.Input.GetData("requestBody").([]byte)
	//fmt.Println("【RequestBody】 ",controller.Ctx.Input.Method(),controller.Ctx.Input.URL(),string(body))
	return json.Unmarshal(body, v)
}

func (controller BaseController) HandlerResponse(data interface{}, err error) {
	var response utils.JsonResponse
	defer func() {
		controller.Data["json"] = response
		controller.ServeJSON()
	}()
	if err == nil {
		response = utils.ResponseData(controller.Ctx, data)
		return
	}
	if _, ok := err.(*application.ServiceError); !ok {
		err = application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	response = utils.ResponseError(controller.Ctx, err)
}

func (controller BaseController) GetLimitInfo() (offset int, limit int) {
	offset, _ = controller.GetInt("offset")
	limit, _ = controller.GetInt("limit")
	return
}