Commit 39f07654 authored by suyanlong's avatar suyanlong

Add api function and gin tool

parent e30d8e60
Pipeline #8303 canceled with stages
package api
import (
"net/http"
"github.com/gin-gonic/gin"
"gitlab.33.cn/link33/sidecar/model/pb"
)
type API interface {
SendTransaction()
GetTransaction()
GetBlockByHash()
GetBlockByNumber()
ListResources()
Call()
}
const (
SendTransaction = "sendTransaction"
GetTransaction = "getTransaction"
GetBlockByHash = "getBlockByHash"
GetBlockByNumber = "getBlockByNumber"
ListResources = "listResources"
Call = "call"
)
// POST 127.0.0.1:80/api/sendTransaction
func (g *Server) sendTransaction(c *gin.Context) {
ibtp := &pb.IBTP{}
var res pb.Response
if err := c.BindJSON(ibtp); err != nil {
res.Data = []byte(err.Error())
c.JSON(http.StatusBadRequest, res)
return
}
//TODO
c.JSON(http.StatusOK, res)
panic("implement me")
}
// GET 127.0.0.1:80/api/getTransaction/:hash
func (g *Server) getTransaction(c *gin.Context) {
panic("implement me")
}
// GET 127.0.0.1:80/api/getBlockByHash/:hash
func (g *Server) getBlockByHash(c *gin.Context) {
panic("implement me")
}
// GET 127.0.0.1:80/api/getBlockByNumber/:height
func (g *Server) getBlockByNumber(c *gin.Context) {
panic("implement me")
}
// GET 127.0.0.1:80/api/listResources
func (g *Server) listResources(c *gin.Context) {
panic("implement me")
}
// POST 127.0.0.1:80/api/call
func (g *Server) call(c *gin.Context) {
panic("implement me")
}
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Error struct {
StatusCode int `json:"-"`
Code int `json:"code"`
Msg string `json:"msg"`
}
var (
Success = NewError(http.StatusOK, 0, "success")
ServerError = NewError(http.StatusInternalServerError, 200500, "system error!")
NotFound = NewError(http.StatusNotFound, 200404, http.StatusText(http.StatusNotFound))
)
func OtherError(message string) *Error {
return NewError(http.StatusForbidden, 100403, message)
}
func (e *Error) Error() string {
return e.Msg
}
func NewError(statusCode, Code int, msg string) *Error {
return &Error{
StatusCode: statusCode,
Code: Code,
Msg: msg,
}
}
// 404
func HandleNotFound(c *gin.Context) {
err := NotFound
c.JSON(err.StatusCode, err)
return
}
func ErrHandler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if length := len(c.Errors); length > 0 {
e := c.Errors[length-1]
err := e.Err
if err != nil {
var Err *Error
if e, ok := err.(*Error); ok {
Err = e
} else if e, ok := err.(error); ok {
Err = OtherError(e.Error())
} else {
Err = ServerError
}
c.JSON(Err.StatusCode, Err)
return
}
}
}
}
//func Timeout() gin.HandlerFunc {
// return func(c *gin.Context) {
// c.Next()
// timeout.New(
// timeout.WithTimeout(100*time.Microsecond),
// timeout.WithHandler(emptySuccessResponse))
// }
//}
//
//func emptySuccessResponse(c *gin.Context) {
// time.Sleep(200 * time.Microsecond)
// c.String(http.StatusOK, "")
//}
...@@ -6,6 +6,10 @@ import ( ...@@ -6,6 +6,10 @@ import (
"net/http" "net/http"
"path/filepath" "path/filepath"
casbin "github.com/casbin/casbin/v2"
"github.com/gin-contrib/authz"
"github.com/gin-contrib/gzip"
"github.com/gin-contrib/requestid"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
appchainmgr "github.com/meshplus/bitxhub-core/appchain-mgr" appchainmgr "github.com/meshplus/bitxhub-core/appchain-mgr"
"github.com/meshplus/bitxhub-kit/crypto/asym" "github.com/meshplus/bitxhub-kit/crypto/asym"
...@@ -34,8 +38,15 @@ type response struct { ...@@ -34,8 +38,15 @@ type response struct {
func NewServer(config *repo.Config, router router.Router, logger logrus.FieldLogger) *Server { func NewServer(config *repo.Config, router router.Router, logger logrus.FieldLogger) *Server {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
// load the casbin model and policy from files, database is also supported.
e, err := casbin.NewEnforcer("authz_model.conf", "authz_policy.csv")
tool.Asset(err)
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
r := gin.New() r := gin.Default()
r.NoMethod(HandleNotFound)
r.NoRoute(HandleNotFound)
r.Use(gzip.Gzip(gzip.DefaultCompression), ErrHandler(), requestid.New(), authz.NewAuthorizer(e))
return &Server{ return &Server{
engine: r, engine: r,
config: config, config: config,
...@@ -49,6 +60,7 @@ func NewServer(config *repo.Config, router router.Router, logger logrus.FieldLog ...@@ -49,6 +60,7 @@ func NewServer(config *repo.Config, router router.Router, logger logrus.FieldLog
func (g *Server) Start() error { func (g *Server) Start() error {
g.engine.Use(gin.Recovery()) g.engine.Use(gin.Recovery())
v1 := g.engine.Group("/v1") v1 := g.engine.Group("/v1")
//g.engine.Use(gin.Recovery())
{ {
v1.POST(client.RegisterAppchainUrl, g.registerAppchain) v1.POST(client.RegisterAppchainUrl, g.registerAppchain)
v1.POST(client.UpdateAppchainUrl, g.updateAppchain) v1.POST(client.UpdateAppchainUrl, g.updateAppchain)
......
...@@ -17,8 +17,7 @@ const ( ...@@ -17,8 +17,7 @@ const (
UpdateAppchainUrl = "appchain/update" UpdateAppchainUrl = "appchain/update"
AuditAppchainUrl = "appchain/audit" AuditAppchainUrl = "appchain/audit"
GetAppchainUrl = "appchain/get" GetAppchainUrl = "appchain/get"
RegisterRuleUrl = "rule/register"
RegisterRuleUrl = "rule/register"
) )
func httpGet(url string) ([]byte, error) { func httpGet(url string) ([]byte, error) {
......
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")
p, alice, /dataset1/*, GET
p, alice, /dataset1/resource1, POST
p, bob, /dataset2/resource1, *
p, bob, /dataset2/resource2, GET
p, bob, /dataset2/folder1/*, POST
p, dataset1_admin, /dataset1/*, *
g, cathy, dataset1_admin
...@@ -78,3 +78,5 @@ func Exist(path string) bool { ...@@ -78,3 +78,5 @@ func Exist(path string) bool {
//https://github.com/casbin/casbin //https://github.com/casbin/casbin
//https://github.com/casbin/casbin //https://github.com/casbin/casbin
//https://github.com/casbin/casbin
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment