DEV Community

Cover image for serverless offline golang setup
NMK
NMK

Posted on

serverless offline golang setup

Recently i have faced an issue in running the serverless application built using GoLang in offline(locally).

So, i just want to share the detailed steps

Initial Setup

Pre requisites

  • Serverless package should be installed globally
  • Golang
  • Make sure you're in your ${GOPATH}/src directory

take a sample application setup from aws examples

$ serverless create -t aws-go-dep -p <your project name>

Add a Makefile in root directory

.PHONY: build clean deploy
build:
    env GOOS=linux go build -ldflags="-s -w" -o <your bunary path>
clean:
    rm -rf ./bin
deploy: clean build
    sls deploy --verbose

Add package.json file in the project root directory

{
    "name": "lambda-golang-offline",
    "description": "To run the golanf lambda service locally",
    "version": "1.0.0",
    "scripts": {
        "start": "node ./node_modules/.bin/serverless offline start --useDocker",
        "watch": "nodemon --watch ./ -e go,js --exec make build"
    },
    "devDependencies": {
        "nodemon": "^2.0.3",
        "serverless": "^1.70.0",
        "serverless-offline": "^6.1.5"
    }
}

Now install the npm dependencies using the command

$ npm i

Now build the binary

$ make build

Now start the server

$ npm start

for the first time it will take time. wait and then hit the api in postman

while development use watch

$ npm run watch

serverless.yaml looks like this

service: returns
frameworkVersion: '>=1.28.0 <2.0.0'
provider:
  name: aws
plugins:
  - serverless-offline
package:
  exclude:
    - ./**
  include:
    - ./bin/**
functions:
  return:
    runtime: go1.x
    handler: <your handler>
    environment:
      env: ${opt:stage, self:provider.stage}
      IS_OFFLINE: false
    events:
      - http: 
          path: /<desires path>
          method: post
          cors:
            origins:
            - "*"
            headers:
            - Content-Type
            - X-Amz-Date
            - Authorization
            - X-Api-Key
            - X-Amz-Security-Token
            - X-Amz-User-Agent

if you are planning to use api gateway endpoints in front end then you should add the cors policy in serverless.yaml file
instaed of * use the relevant origin names

you can find all the files in git

Next Post will be on Serverless lambda setup with typescript and mysql

Top comments (1)

Collapse
 
sushmit19572764 profile image
sushmitha shetty

Waiting for the next post. When it will be posted?