刚刚开始接触Fabric,先从书上例子入手,之后又想模仿着做一个自己的应用,以前接触过Vue,想着前后分离方案,后端只提供api,前端老老实实负责展示
现有的样例是模板渲染方案,我在此基础上更换了接口,使用Gin框架进行api编写(ps:beego玩不转,controllers那里不知道怎样改才能传入实例化的chainapp对象。。)
Gin与原生net/http相比友好了许多,但有给了使用者自己的空间发挥
参考文档:https://www.yoytang.com/go-gin-doc.html
show me the code
package api
import (
"github.com/gin-gonic/gin"
"net/http"
"github.com/myfirstapp/service"
)
type Application struct {
Fabric *service.ServiceSetup
}
func WebStart(app *Application) {
// 初始化引擎
engine := gin.Default()
// 注册一个路由和处理函数
engine.POST("/getinfo", app.GetInfo)
engine.POST("/setinfo", app.SetInfo)
// 绑定端口,然后启动应用
engine.Run(":9205")
}
func (app *Application) GetInfo(context *gin.Context) {
name := context.PostForm("name")
msg, err := app.Fabric.GetInfo(name)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{
"name": name,
})
}else{
context.JSON(http.StatusOK, gin.H{
"msg": msg,
})
}
}
func (app *Application) SetInfo(context *gin.Context) {
name := context.PostForm("name")
num := context.PostForm("num")
transactionID, err := app.Fabric.SetInfo(name, num)
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{
"status": "something wrong...",
})
}else{
context.JSON(http.StatusOK, gin.H{
"msg": transactionID,
})
}
}
在顶层main中添加
app := api.Application{
Fabric: &serviceSetup,
}
api.WebStart(&app)
启动区块链应用,postman测试

返回交易ID(注意提交格式)
完成!!
网友评论