Skip to content

Instantly share code, notes, and snippets.

@aschmidt75
Last active April 3, 2019 10:40
Show Gist options
  • Save aschmidt75/f20667c2e21c866a78d5282754672fa2 to your computer and use it in GitHub Desktop.
Save aschmidt75/f20667c2e21c866a78d5282754672fa2 to your computer and use it in GitHub Desktop.
Blank Fabric golang chaincode template with logging
/**
*/
package main
import (
"encoding/json"
"log"
"os"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
)
var (
logger = log.New(os.Stdout, "PreciousCargoChaincode: ", log.Ldate|log.Ltime|log.Lmicroseconds)
)
type PreciousCargoChaincode struct {
}
type xyzArg struct {
First string `json:"first"`
Second *int `json:"second,omitempty"`
}
func (cci *PreciousCargoChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
logger.Println("enter Init")
// we could process init arguments here using the stub
return shim.Success(nil)
}
func (cci *PreciousCargoChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
logger.Println("enter Invoke")
function, args := stub.GetFunctionAndParameters()
logger.Printf("function=%s, args=%#v", function, args)
if function == "xyz" {
if len(args) != 1 {
return shim.Error("Expecting JSON input as first param")
}
// try unmarshaling the first argument as JSON
a := xyzArg{}
err := json.Unmarshal([]byte(args[0]), &a)
if err != nil {
logger.Printf("Error unmarshaling JSON: %s", err)
return shim.Error("Invalid JSON")
}
// hand over to internal function
return cci.xyz(stub, a)
}
return shim.Error("Invalid function name.")
}
func (cci *PreciousCargoChaincode) xyz(stub shim.ChaincodeStubInterface, arg xyzArg) pb.Response {
logger.Println("enter xyz")
logger.Printf("arg=%#v\n", arg)
// do something DLT transactional here...
// compose a result (e.g. a message)
resp := struct {
msg string
}{"just xyz'ed evrythng."}
r, e := json.Marshal(resp)
if e != nil {
return shim.Error("Internal JSON marshal error.")
}
return shim.Success(r)
}
func main() {
logger.Println("Instantiating chaincode.")
err := shim.Start(new(PreciousCargoChaincode))
if err != nil {
logger.Fatalf("Error starting chaincode: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment