Search code examples
amazon-web-servicesgoaws-lambdaaws-api-gatewaygo-iris

How to deploy REST API to AWS lambda using go-iris framework


I have created REST API using Go Iris framework. Now I want to deploy these API's on AWS with lambda function. I am using MySQL as database. Is it possible to deploy my Go executable file on AWS lambda or should I need to modify my code according to AWS lambda specifications? I am trying to find the solution, but not getting much information.

Here is one of my API end point.

package main

import (
    "database/sql"
    "github.com/kataras/iris"
    "github.com/kataras/iris/middleware/logger"
    "github.com/kataras/iris/middleware/recover"
)

type Reward struct {
    Id int `json:"reward_id"`
    LotteryID int `json:"lottery_id"`
    RewardName string `json:"reward_name"`
    Description string `json:"reward_description"`
    Asset int `json:"reward_asset"`
    AssetName string `json:"reward_asset_name"`
    }

func dbConn() (db *sql.DB) {
    dbDriver := "mysql"
    dbUser := "xxx"
    dbPass := "xxx"
    dbName := "xxx"
    db, err := sql.Open(xxxxxxxxx)
    if err != nil {
    panic(err.Error())
    }
    return db
}


func newApp() *iris.Application {
    app := iris.New()
    app.Logger().SetLevel("debug")

    app.Use(recover.New())
    app.Use(logger.New())
    
    db := dbConn()

    app.Get("/reward/{reward_id:int}", func(ctx iris.Context) {
    id1 := ctx.Params().GetIntDefault("reward_id", 0)


    stmtOut, err := db.Prepare("select id, lottery_id,reward_name,reward_description,reward_asset, reward_asset_name from rewards_table where id =?")
    if err != nil {
    panic(err.Error())
    }
    defer stmtOut.Close()

    var id, lotteryId, rewardAsset int
    var rewardName, rewardDescription, rewardAssetName string

    err1 := stmtOut.QueryRow(id1).Scan(&id, &lotteryId, &rewardName, &rewardDescription, &rewardAsset, &rewardAssetName)
    if err1 != nil {
        panic(err.Error())
    }
    reward := Reward{
        Id:          id,
        LotteryID:   lotteryId,
        RewardName:  rewardName,
        Description: rewardDescription,
        Asset:       rewardAsset,
        AssetName:   rewardAssetName,
    }
    ctx.JSON(&reward)
    })
    return app
}



func main() {
    app := newApp()
    app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed), iris.WithOptimizations)
}

I have few more API endpoints which do basic CRUD operations. I am thinking about using AWS lambda and AWS API Gateway.


Solution

  • should I need to modify my code according to AWS lambda specifications?

    Yes. Your code for lambda will require to have a handler:

    This is the entry point to your function.

    Also it seems that your go program is a web server build on iris. If this is the case, you won't be able to use it anyway, as you can't invoke lambda from internet as you would a regular server.

    Also lambda runs for max 15 minutes, thus its use as a server would be very limited.