Build error in golang package compilation - go

I'm designing an IBM DB2 warehouse database using Go ORM. I include the dependencies
import ( _ "github.com/ibmdb/go_ibm_db" "github.com/jinzhu/gorm" )
and create the database
func Init() \*gorm.DB {
db, err := gorm.Open("ibm_db", dbURL)
if err != nil {
log.Print("Error db init Database.init 19")
panic(err.Error())
}
migrate(db)
return db
}
but I receive this error:
Build Error: go build -o /home/t/skola/programmering/hackYourWorld/api/\__debug_bin -gcflags all=-N -l .
# github.com/ibmdb/go_ibm_db/api
/home/t/go/pkg/mod/github.com/ibmdb/go_ibm_db#v0.4.2/api/api_unix.go:13:11: fatal error: sqlcli1.h: No such file or directory 13 |
// #include \<sqlcli1.h\> | ^\~\~\~\~\~\~\~\~\~\~ compilation terminated. (exit status 2)
I'm running a ubuntu docker container with go1.18.1 and include the package according to the documentation: go get -d github.com/ibmdb/go_ibm_db\
I tried installing it but can't find any possible problem.

Related

Deploy serverless functions to digitalocean in golang

I am trying to build a CRUD in digital ocean serverless functions. I am testing with sqlite3 and insert into the table. When I tried to deploy it to productions, I am getting errors. Here is my code:
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func Main(args map[string]interface{}) map[string]interface{} {
db, err := sql.Open("sqlite3", "./data.db")
checkErr(err)
// insert
stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
checkErr(err)
res, err := stmt.Exec("rumi", "CSE", "2012-12-09")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
db.Close()
msg := make(map[string]interface{})
msg["body"] = id
return msg
}
Errors I am getting:
➜ functions git:(master) ✗ doctl serverless deploy . --remote-build
Deploying '/home/rumi/go/src/github.com/manjurulhoque/digitalocean-cloud-functions/functions'
to namespace 'fn-b799454253a-a40440-4639-937f-05102a48c06e'
on host 'https://fa45as-sgp1-18b45c02afgc.doserverless.co'
Submitted action 'blog/createBlog' for remote building and deployment in runtime go:default (id: b3d5421ee5656bb44c4295421eebb44c642cf)
Submitted action 'sample/hello' for remote building and deployment in runtime go:default (id: b3d5421ee5656bb44c4295421eebb44c642cf)
Submitted action 'blog/db' for remote building and deployment in runtime go:default (id: edcc9eefce9f4aa58c9eefce9f2aa5e6)
Transcript of remote build session for action 'blog/db':
Output of failed build in /tmp/slices/builds/fn-b79956253a-a4080-465639-95637f-05102a48c06e/blog_db/2022-10-22T04-23-08.642Z/packages/blog/db
initializing modules
go: creating new go.mod: module exec
go: to add module requirements and sums:
go mod tidy
building
db.go:6:2: no required module provides package github.com/mattn/go-sqlite3; to add it:
go get github.com/mattn/go-sqlite3
Deployed functions ('doctl sbx fn get <funcName> --url' for URL):
- blog/createBlog
- sample/hello
Failures:
Error: While deploying action 'blog/db': './build.sh' exited with code 1
project.yml
environment: {}
parameters: {}
packages:
- name: blog
environment: {}
parameters: {}
annotations: {}
functions:
- name: db
binary: false
main: ''
runtime: 'go:default'
web: true
parameters: {}
environment: {}
annotations: {}
limits: {}
I didn't find any good resource though to connect to DB. Any help would be appreciated.
In DO, every function itself is an app. So you need to create go.mod and go.sum in each function directoy.
Below is one of my project structure
Note: I wrote an article on how to setup golang app for DO
https://medium.com/#manzurulhoque/use-package-in-digital-ocean-do-serverless-functions-using-golang-cb5200ab22ee

Importing a go package from github that uses native C code

I'm writing some code that needs access to a Cobra CLI object from another GitHub repo:
package main
import (
"github.com/spf13/cobra/doc"
"github.com/sylabs/singularity/cmd/singularity/cli"
"log"
)
func main() {
err := doc.GenReSTTree(cli.SingularityCmd, "./")
if err != nil {
log.Fatal(err)
}
}
I also have the following version constraint:
[[constraint]]
name = "github.com/sylabs/singularity"
version = "3.0.3"
Now, when I go install, I get the error:
# github.com/TMiguelT/singularity-userdocs/vendor/github.com/sylabs/singularity/internal/pkg/runtime/engines/config/starter
vendor/github.com/sylabs/singularity/internal/pkg/runtime/engines/config/starter/starter.go:10:10: fatal error: starter.h: No such file or directory
#include "starter.h"
^~~~~~~~~~~
compilation terminated.
So when I try to build my code, it tries to compile the singularity module and fails because it can't find some C code. This header file is located here in the repo I'm importing: https://github.com/sylabs/singularity/blob/v3.0.3/cmd/starter/c/starter.h
How can I make my go install aware of this, to ensure my project compiles?

Why does proto marshal then unmarshal fail when it is run outside of project containing vendor directory?

I have a main.go file that uses the proto files in pkg/models to Marshal and Unmarshal a proto struct like this:
// Convert to string
protoStr := proto.MarshalTextString(proto)
// Unmarshal string back to proto struct
var proto2 models.Stuff
err := proto.UnmarshalText(protoStr, &proto2)
The setup is here: https://github.com/chuyval/qqs/tree/master/q2
The project contains a vendor directory that only has the github.com/golang/protobuf repo checked out. (run glide install to create vendor if it doesnt exist)
The main.go program works fine when running go run main.go from inside the project.
When I move the main.go file one level up to the parent directory, and run the same command go run main.go at the parent level, it reports the following error:
line 2: unknown field name "value_list" in models.Stuff
When I delete the vendor directory in the project directory, and run go run main.go at the parent level, I get no error.
Why would having a vendor directory in the project repository make it error out?
Another thing to note, if I run the same main.go application inside of the dependent repo, it works every time (with or without the vendor repository).
Sample code:
package main
import (
"github.com/chuyval/qqs/q2/pkg/models"
"github.com/golang/protobuf/proto"
"log"
)
func main () {
stuff := createProtoStuff()
log.Printf("Stuff: %+v", stuff)
// Convert to string
stuffStr := proto.MarshalTextString(stuff)
// Unmarshal string back to proto struct
var stuff2 models.Stuff
err := proto.UnmarshalText(stuffStr, &stuff2)
if err != nil {
log.Printf("It didnt work. Error: %s", err.Error())
} else {
log.Printf("It worked. Proto: %+v", stuff2)
}
}
func createProtoStuff() *models.Stuff {
someValueList := []*models.SomeValue{&models.SomeValue{Id: "Some Value ID"}}
valueList := &models.SomeValueList{SomeValue: someValueList}
stuffValueList := &models.Stuff_ValueList{
ValueList: valueList,
}
stuff := &models.Stuff{
Id: "Stuff List Id",
Stuff: stuffValueList,
}
return stuff
}
Software Versions
glide version 0.13.1
go version go1.10.3 darwin/amd64
protoc version libprotoc 3.6.0

Error building chaincode written in go

When I try to modify the example described in this hyperledger example I get some error when adding this external library in order to get the History of the chaincode state.
Why does that happen?
I add the library with govendor, but when I run this command:
docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin#org1.example.com/msp" cli peer chaincode instantiate -o orderer.example.com:7050 -C mychannel -n $CC_NAME -l "$LANGUAGE" -v 1.0 -c $INIT_STR -P "OR ('Org1MSP.member','Org2MSP.member')"
I get this error:
Error: Error endorsing chaincode:
rpc error: code = Unknown desc = error starting container: Failed to generate platform-specific docker build: Error returned from build: 2 "# firstExample
chaincode/input/src/firstExample/firstStep.go:104:11: cannot assign *"github.com/hyperledger/fabric/protos/ledger/queryresult".KeyModification to kM (type *"firstExample/vendor/github.com/hyperledger/fabric/protos/ledger/queryresult".KeyModification) in multiple assignment
chaincode/input/src/firstExample/firstStep.go:146:11: cannot assign *"github.com/hyperledger/fabric/protos/ledger/queryresult".KeyModification to kM (type *"firstExample/vendor/github.com/hyperledger/fabric/protos/ledger/queryresult".KeyModification) in multiple assignment
chaincode/input/src/firstExample/firstStep.go:156:11: cannot assign *"github.com/hyperledger/fabric/protos/ledger/queryresult".KeyModification to kM (type *"firstExample/vendor/github.com/hyperledger/fabric/protos/ledger/queryresult".KeyModification) in multiple assignment
I have some troubles with this. I'm sure that the library is imported because if I build the chaincode written in go with the command:
go build
I get no errors.
Please help me!
It's very hard to guess without seeing actual code which cause the compilation error, while it seems that you are not taking care of the second parameter which returned by HistoryQueryIteratorInterface#Next() API or even ChaincodeStubInterface#GetHistoryForKey(). Please see example of how to use those APIs correctly:
// GetPreviousValue reads previous value of given key
func (pm *personManagement) GetPreviousValue(params []string, stub shim.ChaincodeStubInterface) peer.Response {
historyIer, err := stub.GetHistoryForKey(params[0])
if err != nil {
errMsg := fmt.Sprintf("[ERROR] cannot retrieve history of key <%s>, due to %s", params[0], err)
fmt.Println(errMsg)
return shim.Error(errMsg)
}
if historyIer.HasNext() {
modification, err := historyIer.Next()
if err != nil {
errMsg := fmt.Sprintf("[ERROR] cannot read key record modification, key <%s>, due to %s", params[0], err)
fmt.Println(errMsg)
return shim.Error(errMsg)
}
fmt.Println("Returning information about", string(modification.Value))
return shim.Success(modification.Value)
}
fmt.Printf("No history found for key %s\n", params[0])
return shim.Success([]byte(fmt.Sprintf("No history for key %s", params[0])))
}
NOTE: Please pay attention that historyIer.Next() returns history value and the error.

Golang on OpenShift, I can't find local module

I want to use an OpenShift test environment for my Golang applications.
I made a test application:
myproj/
------web.go
------/mylib/
-------------mylib.go
web.go is standard OpenShift file:
package main
import (
"fmt"
"net/http"
"os"
"runtime"
"./mylib"
)
func main() {
http.HandleFunc("/", hello)
bind := fmt.Sprintf("%s:%s", os.Getenv("HOST"), os.Getenv("PORT"))
fmt.Printf("listening on %s...", bind)
err := http.ListenAndServe(bind, nil)
if err != nil {
panic(err)
}
}
func hello(res http.ResponseWriter, req *http.Request) {
str := mylib.Lib();
fmt.Fprintf(res, "hello, %s from %s", str, runtime.Version())
}
and I created "mylib"
package mylib
func Lib() string {
return "world"
}
and when I run "go run web.go" everything works fine on my local computer. But when I try to upload this code to OpenShift I get the following error:
remote: -----> Using Go 1.1.2
remote: -----> Running: go get -tags openshift ./...
remote: can't load package: /var/lib/openshift/5354e6fd4382ec2dca000223/app-root/runtime/repo/.openshift/g/src/github.com/smarterclayton/goexample/web.go:8:2: local import "./mylib" in non-local package
remote: An error occurred executing 'gear postreceive' (exit code: 1)
remote: Error message: CLIENT_ERROR: Failed to execute: 'control build' for /var/lib/openshift/5354e6fd4382ec2dca000223/go
What does this mean? Why can't Golang find this package? I can't write all code in one file. How should I write the application for OpenShift?
I know this question is old but i had the same problem and it was difficult to find the solution, so i decided to ask in order to help who will run on the same problem.
The solution is very simple and can be found in readme of the go cartdrige repo on github: github.com/smarterclayton/openshift-go-cart
You have to create a file named .godir and put here the name of the main package of your server.
For example if you put myserver you can use:
package main
import "myserver/mylib"
func main() {
mylib.DoStuff()
}
Basically when you push on openshift the repo is copied in the directory placed in .godir before the build

Resources