minerva/gateway/pkg/apiserver/apiserver.go

152 lines
3.1 KiB
Go

package apiserver
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
grpcv1 "minerva.bing89.com/gateway/pkg/grpc/v1"
"minerva.bing89.com/gateway/pkg/minerva"
)
//响应数据结构
type ResponseMessage struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
//APIServer 提供api接口
type APIServer struct {
// minervas minerva.Minervas
grpcv1.Server
}
func NewAPIServer(svr grpcv1.Server)*APIServer{
return &APIServer{
Server: svr,
}
}
//Ajax式响应
func (a *APIServer)response(c *gin.Context,code int, m string, v interface{}){
c.JSON(http.StatusOK, ResponseMessage{Code: code, Message: m, Data: v})
}
//成功,返回数据
func (a *APIServer)success(c *gin.Context, v interface{}){
a.response(c, 0, "success", v)
}
//失败,返回错误
func (a *APIServer)error(c *gin.Context, e error){
a.response(c, 1000, e.Error(), nil)
}
//功能正在开发中
func (a *APIServer)functionInDeving(c *gin.Context){
a.error(c, fmt.Errorf("功能正在开发中"))
}
// 列出当前已注册的Minervas
// @router [GET] /minervas
// @example /api/v1/minervas
func (a *APIServer)ListMinervas(c *gin.Context){
minervas, err := a.Minervas.List()
if err != nil {
a.error(c, err)
return
}
a.success(c, minervas)
}
// 查看指定的Minerva信息
// @router [GET] /minervas/:name
// @example /api/v1/minervas/aaa
func (a *APIServer)GetMinerva(c *gin.Context){
name := c.Param("name")
m, err := a.Minervas.Get(name)
if err != nil {
a.error(c, err)
return
}
a.success(c, m)
}
// 注册一个Minerva
// @router [POST] /minervas
// @example /api/v1/minervas
// {}
//
func (a *APIServer)CreateMinerva(c *gin.Context){
a.functionInDeving(c)
}
// 更新一个Minerva
// @router [PUT] /minervas/:name
// @example /api/v1/minervas/aaa
// {}
//
func (a *APIServer)UpdateMinerva(c *gin.Context){
a.functionInDeving(c)
}
// 删除一个Minerva
// @router [DELETE] /minervas/:name
// @example /api/v1/minervas/aaa
// {}
//
func (a *APIServer)DeleteMinerva(c *gin.Context){
a.functionInDeving(c)
}
// 执行minerva
// @router [POST] /minervas/:name/run
// @example /api/v1/minervas/aaa/run
// {}
//
func (a *APIServer)RunMinerva(c *gin.Context){
name := c.Param("name")
m, err := a.Minervas.Get(name)
if err != nil {
a.error(c, err)
return
}
defer c.Request.Body.Close()
data := []byte{}
_, err = c.Request.Body.Read(data)
if err != nil {
a.error(c, err)
return
}
clt, err := grpcv1.NewInsecureClient(m)
if err != nil {
a.error(c, err)
return
}
resp, err := clt.Call(&minerva.Request{Bytes: data})
if err != nil {
a.error(c, err)
return
}
if resp.Success {
a.success(c, resp.Bytes)
return
}
a.error(c, fmt.Errorf(resp.Error))
}
//初始化route表
func (a *APIServer)InitRoute(engine *gin.Engine){
apiGroup := engine.Group("/api/v1")
apiGroup.GET("/minervas", a.ListMinervas)
minervaGroup := apiGroup.Group("/minervas")
minervaGroup.GET("/:name", a.GetMinerva)
minervaGroup.POST("/:name", a.CreateMinerva)
minervaGroup.PUT("/:name", a.UpdateMinerva)
minervaGroup.DELETE("/:name", a.DeleteMinerva)
minervaGroup.POST("/:name/run", a.RunMinerva)
}