I am new at Golang. I am learning about universal scope and importing variables from one file to another.
Conditions:
System: Windows 11 x64
IDE: VS code
Language: GoLang
According to the universal scope I should be able to import variables from one file to another easily. Primary file: "main.go" and secondary file ""uniscope.go
Importing from uniscope.go into main.go
If the files are kept in the same folder directory then I can easily import using command: "go run main.go uniscope.go"
This runs without any error but until this command I get the error in main.go, "undeclared name", that is still not the main issue.
When I move the uniscope.go to another folder and then I run "go run main.go uniscope.go", it doesn't work, which is understandable as directory has been changed. So then I copy the path and paste it in import which in turns resolves the previous error, change the command to "go run main.go" but it throws out a new one.
"main.go:6:7: illegal character U+0073 's' in escape sequence"
I am not sure how I am wrong here. The video I am learning from is: https://www.youtube.com/watch?v=vYD9XWi_Xw8&list=PLve39GJ2D71xX0Ham0WoPaYfl8oTzZfN6&index=5
He is using itelliJ but I don't think that should be an issue.
I have tried the mentioned above and also tried finding the exact error on google. Just found a similar question posted on some Portuguese forum with no answers.
main.go:
package main
import "hello/world"
func main() {
println(world.Value)
}
world/world.go:
package world
const Value = 1
and run:
go mod init hello
go run .
Getting error fork/exec /var/task/main: no such file or directory while executing lambda function.
I am using windows platform to run and build code in Go.
I have done following steps to deploy go aws-lambda handler:
Written code in go language with VSCode in windows platform
Build project with : go build main.go
Convert main.exe to main.zip
Uploaded main.zip with handler name main aws-lambda fuction using aws console account
Created test event to test lambda function
Got error "fork/exec /var/task/main: no such file or directory while executing lambda function"
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
)
// Request represents the requested object
type Request struct {
ID int `json:"ID"`
Value string `json:"Value"`
}
// Response represents the Response object
type Response struct {
Message string `json:"Message"`
Ok bool `json:"Ok"`
}
// Handler represents the Handler of lambda
func Handler(request Request) (Response, error) {
return Response{
Message: fmt.Sprint("Process Request Id %f", request.ID),
Ok: true,
}, nil
}
func main() {
lambda.Start(Handler)
}
build command
go build main.go
Detail Error in AWS console
{
"errorMessage": "fork/exec /var/task/main: no such file or directory",
"errorType": "PathError"
}
Log Output in AWS console
START RequestId: 9ef206ed-5538-407a-acf0-06673bacf2d7 Version: $LATEST
fork/exec /var/task/main: no such file or directory: PathError
null
END RequestId: 9ef206ed-5538-407a-acf0-06673bacf2d7
REPORT RequestId: 9ef206ed-5538-407a-acf0-06673bacf2d7 Duration: 0.64 ms Billed Duration: 100 ms Memory Size: 512 MB Max Memory Used: 31 MB Init Duration: 1.49 ms
In my case the problem was default setted handler to 'hello' function.
Needed to change it to 'main' via AWS Lambda view panel -> Basic Settings -> Edit.
Run following commands in command prompt
set GOOS=linux
set GOARCH=amd64
set CGO_ENABLED=0
After this , build your project and upload zip file to aws console lambda
like this
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go
Reference Link : https://github.com/aws/aws-lambda-go
There are two reasons can happen:
You did't use GOOS=linux GOARCH=amd64 with go build, so try:
GOOS=linux GOARCH=amd64 go build -o main main.go
You used to build this programm some CI function with golang-alpine base image, so try to use full golang image instead.
Recently I was facing similar issue, and I solved it. As the error says it s finding executable with handle name, so you should name your executable same as handler.
Follow these steps and your will not get this error, I am using PowerShell
> go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip # If you do not this have utility earlier
> $env:GOOS = "linux"
> $env:GOARCH = "amd64"
> $env:CGO_ENABLED = "0"
> go build -o .\Handler .\main.go # considering your are in the same directory where your main.go or handler code is present
> ~\Go\Bin\build-lambda-zip.exe -o .\Handler.zip .\Handler
Upload this code, and change handler name to Handler(name of the executable that you created above)
Let me know if this helps.
In my embarrasing case I was zipping the folder from outside so the path in the zip I was uploading was 'folder/main'
You can find the description when you click AWS Lambda > Functions > <Your function name> > Handler info
You can tell the Lambda runtime which handler method to invoke by
setting the handler parameter on your function's configuration.
When you configure a function in Go, the value of the handler setting
is the executable file name. For example, using Handler would call the
function in the package main of the Handler executable file.
It means that your file which has a handler function is not necessarily named main.go. My Handler on AWS is hello and I use this command to create executable file GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o hello hello.go
Here is my case. I am learning Terraform to deploy AWS Lambda function.
I am following an terraform official document to deploy a hello function.
The page guides me to create a function using Node.js and I rewrite it using Go.
Here is my modified part of main.tf.
resource "aws_lambda_function" "hello_world" {
function_name = "HelloWorld"
s3_bucket = aws_s3_bucket.lambda_bucket.id
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "go1.x"
handler = "hello"
source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256
role = aws_iam_role.lambda_exec.arn
}
I deleted the hello.js file and created the hello.go file.
My hello.go is the same as AWS example
package main
import (
"fmt"
"context"
"github.com/aws/aws-lambda-go/lambda"
)
type MyEvent struct {
Name string `json:"name"`
}
func HandleRequest(ctx context.Context, name MyEvent) (string, error)
{
return fmt.Sprintf("Hello %s!", name.Name ), nil
}
func main() {
lambda.Start(HandleRequest)
}
After deploying the lambda function using terraform, we can verify it.
% aws lambda invoke --region=us-east-1 --function-name=HelloWorld response.json
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
I hope this is helpful.
My issue (I think) was the zipping tool / GOOS=windows was set wrong.
Zip Go file using AWS Lambda Tool
My setup is windows + following a golang tutorial. Published to lambda, all appeared fine, got the error and was correctly named and built etc.
I think it's the zipping tool, using build-lambda-zip and now it works for me. Note: I tried using another command to get the tool
go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip however this didn't actually get the tool for me.
Hopefully this saves someone else half an hour of googling
In my case it was related to my Go setting.
As I use Go Version Manager, I had to run the following to specify the right Go path before compiling my project.
gvm use go1.x.x
Proceed to compile then deploy.
My case was a strange one, but I'll leave it here in case someone needs it.
I built my executable in a Docker container and then used Docker cp to put the file in a local directory. Then I zipped the executable and deployed it.
Apparently, Docker cp creates a symlink-like file rather than an actual file, so it just wouldn't work.
My solution was just to use sudo cp and copy the executable as another file, which created a physical file, and deployed that instead.
This error has nothing to do with the program; it's a configuration issue.
Please try to give the complied go file name in the lambda console under Go Runtime settings -
In my case my go lambda compiled file is test so configured Handler as test and it worked for me.
Example Configuration
In my case, the solution is very simple.
I was wrong with the command build.
what I did was go build . instead of go build main.go
the zip file should be main.zip.
and the handler info section in console AWS should be named main.
not handler because lambda calls the main function first
If deploying with SAM cli, make sure to run "sam build" before the "sam deploy"
In my case this had to do with the image I was using to build the go binaries. I switched from using alpine to using amazon linux 2 and the problem was solved.
setting environment variable CGO_ENABLED to 0 solved my problem, this is when using sam local start-api to locally test endpoint
Following is the function written in go:
func LaunchApplication(packageName string) {
Query :
how can I execute application with given packageName
}
Generated the java binding [.aar] using gomobile.
I want to include .aar generated in my android application and call LaunchApplication("com.package.name") from java layer to native go layer and go layer should run the application.
In java application, following is the way to run apk using package name:
Process process = Runtime.getRuntime().exec("am start -n com.package.name/com.package.name.ActivityName");
I tried the same in go using:
os.exec() function but it is giving error that "am not found in the $PATH"
Is there is any other way to do that ?
In android, you should specify the path "/system/bin/"(/system/bin/am). Please make sure there are "am" in this path.
We wrote some Go code to talk to our Kubernetes cluster and fetch the IP of a Service exposed. We do it like so:
(import "gopkg.in/kubernetes/kubernetes.v1/pkg/client/restclient")
(import kubectl "gopkg.in/kubernetes/kubernetes.v1/pkg/client/unversioned")
svc, err := c.Services(k8sNS).Get(svcName)
if err != nil {
panic(l.Errorf("Could not retrieve svc details. %s", err.Error()))
}
svcIP := svc.Status.LoadBalancer.Ingress[0].IP
go get works fine, and our script executes when we do go run ... and everybody is happy. Now, as of yesterday (from the time this question is posted) on the same script - go get fails. The error is like so:
[09.07.2016 10:56 AM]$ go get
package k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install: cannot find package "k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install" in any of:
/usr/local/go/src/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install (from $GOROOT)
/home/ckotha/godir/src/k8s.io/kubernetes/pkg/apis/authentication.k8s.io/install (from $GOPATH)
We have not specifically used authentication package in our code. Are we importing kubernetes libraries correctly? is there another way to do this ?
ls on $GOPATH/k8s.io/kubernetes/pkg/apis/ and found this:
:~/godir/src/k8s.io/kubernetes/pkg/apis
[09.07.2016 10:53 AM]$ ls
abac apps authentication authorization autoscaling batch certificates componentconfig extensions imagepolicy OWNERS policy rbac storage
It looks like a package you imported has changed.
You can update existing repositories:
go get -u
The -u flag instructs get to use the network to update the named
packages and their dependencies. By default, get uses the network to
check out missing packages but does not use it to look for updates to
existing packages.
You do use gopkg.io to pin the version to v1, but I think you want to be more specific, eg, v1.3.6 (EDIT: this won't work because gopkg.in doesn't permit package selectors more specific than the major version.).
Alternatively, a good way to ensure code stays the same is to compile your binary and execute that, instead of using go run.
This question is a follow up to an earlier question of mine. I've closed the question so I hope its okay that I ask a fresh but related question here. Go: embed static files in binary
How do I serve JS files with go-bindata? Do I pass it into html like this
hi.html
<script>{{.Bindata}}></script>
Doesn't seem to work even though I have no compile or JS errors.
Using https://github.com/elazarl/go-bindata-assetfs
Assuming you have the following structure:
myprojectdirectory
├───api
├───cmd
├───datastores
└───ui
├───css
└───js
Where ui is the directory structure you'd like to wrap up and pack into your app...
Generate a source file
The go-bindata-assetfs tool is pretty simple. It will look at the directories you pass to it and generate a source file with variables that can contain the binary data in those files. So make sure your static files are there, and then run the following command from myprojectdirectory:
go-bindata-assetfs ./ui/...
Now, by default, this will create a source file in the package main. Sometimes, this is ok. In my case, it isn't. You can generate a file with a different package name if you'd like:
go-bindata-assetfs.exe -pkg cmd ./ui/...
Put the source file in the correct location
In this case, the generated file bindata_assetfs.go is created in the myprojectdirectory directory (which is incorrect). In my case, I just manually move the file to the cmd directory.
Update your application code
In my app, I already had some code that served files from a directory:
import (
"net/http"
"github.com/gorilla/mux"
)
// Create a router and setup routes
var Router = mux.NewRouter()
Router.PathPrefix("/ui").Handler(http.StripPrefix("/ui", http.FileServer(http.Dir("./ui"))))
// Start listening
http.ListenAndServe("127.0.0.1:3000", Router)
Make sure something like this works properly, first. Then it's trivial to change the FileServer line to:
Router.PathPrefix("/ui").Handler(http.StripPrefix("/ui", http.FileServer(assetFS())))
Compile the app
Now you have a generated source file with your static assets in them. You can now safely remove the 'ui' subdirectory structure. Compile with
go install ./...
And you should have a binary that serves your static assets properly.
Use https://github.com/elazarl/go-bindata-assetfs
From the readme:
go-bindata-assetfs data/...
In your code setup a route with a file server
http.Handle("/", http.FileServer(assetFS()))
Got my answer here: Unescape css input in HTML
var safeCss = template.CSS(`body {background-image: url("paper.gif");}`)