From 98447ef1448b5815d9f1c08f798656f0889c9ddb Mon Sep 17 00:00:00 2001 From: canepat <16927169+canepat@users.noreply.github.com> Date: Tue, 9 Apr 2024 13:04:13 +0200 Subject: [PATCH] capi: fix sample Golang client (#1956) Fix the init settings in our Go sample code using the C API library and improve error handling. --- cmd/capi/sample-go-client/main.go | 44 ++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/cmd/capi/sample-go-client/main.go b/cmd/capi/sample-go-client/main.go index b61d0ba28b..582566bfd5 100644 --- a/cmd/capi/sample-go-client/main.go +++ b/cmd/capi/sample-go-client/main.go @@ -4,21 +4,51 @@ package main // #cgo LDFLAGS: -L${SRCDIR}/../../../build/silkworm/capi // #cgo LDFLAGS: -Wl,-rpath ${SRCDIR}/../../../build/silkworm/capi // #cgo CFLAGS: -I${SRCDIR}/../../../silkworm/capi -// #include "silkworm.h" +/* +#include "silkworm.h" +#include +#include + +static bool go_string_copy(_GoString_ s, char *dest, size_t size) { + size_t len = _GoStringLen(s); + if (len >= size) return false; + const char *src = _GoStringPtr(s); + strncpy(dest, src, len); + dest[len] = '\0'; + return true; +} +*/ import "C" import "fmt" import "os" func main() { + dataDirPath := os.Getenv("HOME") + libMdbxVersion := C.GoString(C.silkworm_libmdbx_version()) + var handle C.SilkwormHandle settings := &C.struct_SilkwormSettings{} - if C.silkworm_init(&handle, settings) != C.SILKWORM_OK { - fmt.Fprintln(os.Stderr, "silkworm_init failed") - return + if !C.go_string_copy(dataDirPath, &settings.data_dir_path[0], C.SILKWORM_PATH_SIZE) { + fmt.Fprintln(os.Stderr, "silkworm.New failed to copy dataDirPath") + os.Exit(1) + } + if !C.go_string_copy(libMdbxVersion, &settings.libmdbx_version[0], C.SILKWORM_GIT_VERSION_SIZE) { + fmt.Fprintln(os.Stderr, "silkworm.New failed to copy libMdbxVersion") + os.Exit(2) } - if C.silkworm_fini(handle) != C.SILKWORM_OK { - fmt.Fprintln(os.Stderr, "silkworm_fini failed") - return + + initResult := C.silkworm_init(&handle, settings) + if initResult != C.SILKWORM_OK { + fmt.Fprintln(os.Stderr, "silkworm_init failed:", initResult) + os.Exit(int(initResult)) + } + + finiResult := C.silkworm_fini(handle) + if finiResult != C.SILKWORM_OK { + fmt.Fprintln(os.Stderr, "silkworm_fini failed:", finiResult) + os.Exit(int(finiResult)) } + + os.Exit(0) }