Go実装RESTful_API追加フィールド
17351 ワード
Go実装RESTful_API追加フィールド
cd $GOPATH/src/github.com/kongyixueyuan.com/education/service
ここにいるよgoに構造体を追加するには:
type User struct {
UserName string `json:"username"`
PassWord string `json:"password"`
Age string `json:"age"`
Phone string `json:"phone"`
Email string `json:"email"`
}
ではgoにメソッドを追加するには:
func (t *ServiceSetup) SaveUser(user User) (string, error) {
eventID := "eventAddUser"
reg, notifier := regitserEvent(t.Client, t.ChaincodeID, eventID)
defer t.Client.UnregisterChaincodeEvent(reg)
// edu
b, err := json.Marshal(user)
if err != nil {
return "", fmt.Errorf(" edu ")
}
req := channel.Request{
ChaincodeID: t.ChaincodeID, Fcn: "addUser", Args: [][]byte{
b, []byte(eventID)}}
respone, err := t.Client.Execute(req)
if err != nil {
return "", err
}
err = eventResult(notifier, eventID)
if err != nil {
return "", err
}
return string(respone.TransactionID), nil
}
cd $GOPATH/src/github.com/kongyixueyuan.com/education/chaincode
eduStruct.goに構造体を追加するには:
type User struct {
UserName string `json:"username"`
PassWord string `json:"password"`
Age string `json:"age"`
Phone string `json:"phone"`
Email string `json:"email"`
}
eduCCでgoにメソッドを追加するには:
func (t *EducationChaincode) addUser(stub shim.ChaincodeStubInterface, args []string) peer.Response {
if len(args) != 2{
return shim.Error(" ")
}
var user User
err := json.Unmarshal([]byte(args[0]), &user)
if err != nil {
return shim.Error(" ")
}
// : na
_, exist := GetEduInfo11(stub, user.UserName)
if exist {
return shim.Error(" ")
}
_, bl := PutEdu11(stub, user)
if !bl {
return shim.Error(" ")
}
err = stub.SetEvent(args[1], []byte{
})
if err != nil {
return shim.Error(err.Error())
}
return shim.Success([]byte(" "))
}
func PutEdu11(stub shim.ChaincodeStubInterface, user User) ([]byte, bool) {
//edu.ObjectType = DOC_TYPE
b, err := json.Marshal(user)
if err != nil {
return nil, false
}
// edu
err = stub.PutState(user.UserName, b)
if err != nil {
return nil, false
}
return b, true
}
func GetEduInfo11(stub shim.ChaincodeStubInterface, userName string) (User, bool) {
var user User
//
b, err := stub.GetState(userName)
if err != nil {
return user, false
}
if b == nil {
return user, false
}
//
err = json.Unmarshal(b, &user)
if err != nil {
return user, false
}
//
return user, true
}
テスト: