I have a go API setup using Serverless. In my root directory I have main.go
and .env
, as well as a config
folder which contains config.go
. I’m having issues as my attempts to access the endpoint throws a runtime error due to it being unable to access the environment variables once deployed (works fine locally).
When I deploy to AWS, and test out the endpoint I get: Failed to load env file: open ./.env: no such file or directory
. How do I fix this issue?
Within config.go
I have:
package config
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func config(key string) string {
if err := godotenv.Load("./.env"); err != nil {
log.Fatalf("Failed to load env file: %v", err)
}
return os.Getenv(key)
}
This function is used, for example, to get the database connection string when setting up my DB connection.
My serverless.yml
is:
service: my_service
frameworkVersion: ">=4.0.32"
useDotenv: true
provider:
name: aws
runtime: provided.al2
architecture: arm64
region: ap-southeast-1
stage: ${opt:stage}
environment:
DB_STRING: ${env:DB_STRING}
HOST_URL: ${env:URL}
HOST_API_KEY: ${env:API_KEY}
# Other env vars...
plugins:
- serverless-plugin-go
- serverless-dotenv-plugin
functions:
api:
handler: main.go
events:
- http:
path: /healthcheck
method: GET
package:
patterns:
- "!*/**"
- bin/bootstrap