Blockchain web application programming to realize the controller

The preparation of the blockchain controller

In the previous article, we implemented the routing for writing blockchain web applications, through train, so this time we will talk about the preparation of blockchain web application controllers. Before writing the controller, we need to check that it needs to be used Whether the dependency package of the golang that arrives exists, otherwise, the controller cannot be written. The dependency package is as follows: golang dependency package We can write the controller code when we make sure that the dependency package exists.
The controller is some method code block to realize the function. The guide package does not need to be written by ourselves. (except for some specific ones) goalnd will help us automatically guide the package. We can use a structure as a controller file and write a method in it to realize the operation of the account book. Let’s look at it directly. Code.

package controller//这个包名是项目结构的文件夹

import (
	"agricultural/application/lib"//这个是整个项目的结构体文件
	"bytes"
	"encoding/json"
	bc "agricultural/application/blockchain"//这个便是整个项目文件的sdk了sdk编写可参照之前文章
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 这里是公司录入一个资产
func CreateAssets(ctx *gin.Context)  {
    
    
	companyId := ctx.Query("companyId")
	// 解析结构体
	req := new(lib.Assets)//解析lib里面的Assets结构体
	if err := ctx.ShouldBind(req); err != nil {
    
    
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
		return
	}
	marshal, _ := json.Marshal(req)//序列化req
	resp, err := bc.ChannelExecute("createAssets", [][]byte{
    
    
	//这边是ChannelExecute不知道大家还有没有印象,在sdk编写中写的一个方法,,当有保存删除修改的操作时都是使用此方法,不能使用ChannelQuery不然会报错。
		marshal,
		[]byte(companyId),
	})
	if err != nil {
    
    //抛出异常
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}
// 查询公司  这个同上面一样唯一不一样的便是 ChannelQuery 查询操作都是使用此方法
func QueryCompany(ctx *gin.Context)  {
    
    
	companyId := ctx.Query("companyId")
	resp, err := bc.ChannelQuery("queryCompany", [][]byte{
    
    
		[]byte(companyId),
	})
	if err != nil {
    
    
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.String(http.StatusOK, bytes.NewBuffer(resp.Payload).String())
}

So today the preparation of the blockchain web controller is here. When I have time, I will give a detailed tutorial on building a network and chaincode with Hyperledger Fabric.
Let's work hard together!

Guess you like

Origin blog.csdn.net/sl331639/article/details/115008819