I'm trying to call another lambda function using the following code:
sess := session.Must(
session.NewSessionWithOptions(
session.Options{
SharedConfigState: session.SharedConfigEnable,
},
),
)
svc := lambda.New(sess, &aws.Config{Region: aws.String("ap-east-1")})
result, err := svc.Invoke(&lambda.InvokeInput{
FunctionName: aws.String(os.Getenv("testLambdaFunc")),
Payload: []byte(req.Body),
})
But there are two errors
New not declared by package lambda
and
InvokeInput not declared by package lambda
I've tried to initialize the go.mod file, but it doesn't fix both of the errors.
Any ideas?
The imports of my main.go file:
"fmt"
"os"
"pkg/log"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
And the go.mod file
module somefunc
go 1.16
require (
github.com/aws/aws-lambda-go v1.27.0
github.com/aws/aws-sdk-go v1.40.59
pkg/log v0.0.0-00010101000000-000000000000
)
replace pkg/log => ./../../go/common/pkg/log
Based on your code snipped, it looks as if you are using the AWS SDK for Go V2. It is recommended to use the AWS SDK for Go V2 (please review the Migrating to the AWS SDK for Go V2 documentation).
Please initialize a Go Modules project (as described on the SDK's Github page):
mkdir YOUR-PROJECT
cd YOUR-PROJECT
go mod init YOUR-PROJECT
Add the dependencies as follows:
go get github.com/aws/aws-sdk-go-v2/aws
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/lambda
The above should give you a working project where the dependencies for the SDK packages will resolve.
The corresponding V2 code will look something like the following:
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("us-east-1"),
)
if err != nil {
[...]
}
svc := lambda.NewFromConfig(cfg)
result, err := svc.Invoke(context.TODO(),
&lambda.InvokeInput{
FunctionName: aws.String(os.Getenv("testLambdaFunc")),
Payload: []byte(req.Body),
},
)
Related
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
I have updated go from v1.14 to 1.16 and now my generated go proto rise build errors.
My project structure:
project_folder
|-- proto_folder
|--data.proto
|--data.pb.go
|--client
|--client.go
|--main.go
When I try to import proto_folder in client/client.go:
import(
pb "project_folder/proto_folder"
"net/http"
"net/url"
)
func SendData(data *DataContainer) {
requestAddr := "http://localhost:8080/data"
out, err := proto.Marshal(data)
req, err := http.NewRequest("POST", requestAddr, bytes.NewBuffer(out))
//exec request with http client
.....
}
I get the error from the IDE (Goland):
Build constraints exclude all Go files in '/usr/local/go/src/project_folder/proto_folder'
When I try to build with go build I get this error:
package project_folder
imports project_folder/client
imports project_folder/proto_folder: no Go files in /usr/local/go/src/project_folder/proto_folder
I am working on testing an application of mine, for which I need to create temporary files with specific extensions. My goal is to create files in a temp directory that look similar to this example123.ac.json.
In order to do this I am using ioutil.TempDir and ioutil.TempFile.
Here is a small contrived example of what I am doing.
main.go:
package main
func main() {
}
main_test.go:
package main
import (
"fmt"
"io/ioutil"
"os"
"testing"
)
func TestMain(t *testing.T) {
dir, err := ioutil.TempDir("", "testing")
if err != nil {
t.Fatalf("unable to create temp directory for testing")
}
defer os.RemoveAll(dir)
file, err := ioutil.TempFile(dir, "*.ac.json") // Create a temporary file with '.ac.json' extension
if err != nil {
t.Fatalf("unable to create temporary file for testing")
}
fmt.Printf("created the following file: %v\n", file.Name())
}
When I run the tests locally on my Mac with go test the following is outputted from the fmt.Printf is
$ go test
created the following file: /var/folders/tj/1_mxwn350_d2c5r9b_2zgy7m0000gn/T/testing566832606/900756901.ac.json
PASS
ok github.com/JonathonGore/travisci-bug 0.004s
So it works as expected but when I run it in TravisCI the following is outputted from the Printf statement:
created the following file: /tmp/testing768620677/*.ac.json193187872
For some reason it is using the literal asterisk inside TravisCI but not when running on my own computer.
Here is a link to the TravisCI logs if interested.
For completeness here is my .travis.yml:
language: go
go:
- "1.10"
Anyone have any idea what is going on here? Or am I missing something obvious?
The feature of replacing the first asterisk with the random value was added in Go 1.11. It looks like you are using go 1.10 for your Travis CI runs so the asterisk won't be replaced.
I am trying to use Go's plugin system. Even with a very basic example, I'm unable to find any symbols in a compiled plugin. My setup looks like this:
/Users/blah/test-workspace/
src/
main/
main.go
plug/
plug.go
plug.go looks like this:
package main
type B struct {}
func main() {}
From the /Users/blah/test-workspace/ directory, I build this using:
GOPATH="/Users/blah/test-workspace" go build -buildmode plugin plug
This produces p.so inside the root of the GOPATH. Next I try to load this plugin via main/main.go:
package main
import (
"fmt"
"plugin"
"os"
)
func main() {
plugin, err := plugin.Open("plug.so")
if err != nil {
fmt.Printf("Error: %+v\n", err)
os.Exit(1)
}
fmt.Printf("%+v\n", plugin)
}
The output of this code is:
&{pluginpath:plug err: loaded:0xc420088060 syms:map[]}
As you can, the symbol map is empty. What am I doing wrong?
From the plugin docs
A symbol is any exported variable or function
You need to add an exported variable or function in order for your plugin to work.
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