
Serverless Go Webservices Using AWS, Revisited
by Alpha Geek
Sat, Feb 10, 2018
Now that AWS supports Go natively, I have updated my shim that allows API Gateway Requests to be handled as if they were regular http.Handler calls.
Here is a quick rundown on how to use this:
- Separate your configuration of your web service muxer from your call to http.ListenAndServe.
package hello import ( "net/http" ... ) func InitHandler() (http.Handler, error) { mux := http.NewServeMux() mux.HandleFunc("/hello/", func(w http.ResponseWriter, req *http.Request) { // Handle your requests here ... }) return mux, nil }
2. Create your main() for your web service:
```go
package main
import (
"github.com/danapsimer/aws-lambda-shim/examples/helloWorld/hello"
"log"
"net/http"
)
func main() {
handler, _ := hello.InitHandler()
log.Fatal(http.ListenAndServe(":8080", handler))
}
- Create your main() for your lambda handler:
package main import ( "github.com/danapsimer/aws-lambda-shim/examples/helloWorld/hello" "github.com/danapsimer/aws-lambda-shim/aws" ) func init() { shim.NewHttpHandlerShim(hello.InitHandler) } func main() { }
4. Make your executable:
```Makefile
build:
GOOS=linux go build -o handler
pack:
zip handler.zip handler
- Create your lambda function in AWS: (in the directory your handler was built)
aws lambda create-function \ --function-name hello-world-api \ --runtime go1.x --handler handler --zip-file fileb://handler.zip \ --role arn:aws:iam::${AWS_ACCOUNT_ID}:role/lambda_basic_execution
6. Create your API Gateway API:
```bash
aws apigateway import-rest-api \
--body file://examples/helloWorld/swagger.json --region us-east-1
aws lambda add-permission --region us-east-1 \
--function-name hello-world-api --statement-id 5 \
--principal apigateway.amazonaws.com --action lambda:InvokeFunction \
--source-arn 'arn:aws:execute-api:us-east-1:${AWS_ACCOUNT_ID}:3l3za8xwnd/*/*/*'