<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alec Carper on Medium]]></title>
        <description><![CDATA[Stories by Alec Carper on Medium]]></description>
        <link>https://medium.com/@aleccarper?source=rss-170eb8d4ba77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wFyihyhRa0R3pLMA8Y70Dg.png</url>
            <title>Stories by Alec Carper on Medium</title>
            <link>https://medium.com/@aleccarper?source=rss-170eb8d4ba77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:43:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aleccarper/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build and deploy a multi-route, serverless web app with Golang on AWS]]></title>
            <link>https://medium.com/@aleccarper/build-and-deploy-a-multi-route-serverless-web-app-with-golang-on-aws-a76f7575751b?source=rss-170eb8d4ba77------2</link>
            <guid isPermaLink="false">https://medium.com/p/a76f7575751b</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alec Carper]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 22:47:59 GMT</pubDate>
            <atom:updated>2018-08-13T22:47:59.521Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide for building a serverless Go API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lGHHzMSjWBrAHj1VGuXKQ.png" /></figure><p>With the recentish support of Go on AWS Lambda I began tinkering around with building various serverless web apps. As the applications became more complex (requiring more than 1 or 2 routes) the project layout, local development, and deployment became increasingly more difficult. After learning from these these pain points I’ve put together this walk-through for those interested in getting a real app up and running quickly.</p><p><a href="https://github.com/aleccarper/serverless-eventbus">For over achievers who learn best by shifting through an example app you can find the completed application on GitHub.</a></p><h3>What We’ll Be Building</h3><p>This article will walk you through building an event bus and deploying it to AWS. Our event bus will have 3 routes that will allow you to:</p><ul><li>POST /subscriptions — Subscribe event types to be routed to an endpoint. This route will accept event_type and endpoint parameters.</li><li>POST /events — Deliver the event’s data to all applicable subscription endpoints via a POST. This route accepts event_type and payload.</li><li>DELETE /subscriptions/{id} — Delete a subscription by ID.</li></ul><p>To ensure that not just anyone can use our event bus we will also be adding authentication by checking an Authorization header value.</p><h3>How Can We Easily Tackle All This?</h3><p>We’ll be using several exciting technologies to build and deploy our event bus. <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> and <a href="https://aws.amazon.com/api-gateway/">AWS API Gateway</a> will be used to host and execute our code. For handling authentication and easily rendering responses for our routes we will use <a href="https://github.com/awslabs/aws-lambda-go-api-proxy">Lambda Go API Proxy</a> to utilize <a href="https://gin-gonic.github.io/gin/">Gin Gonic</a>.</p><p>For local development we can use <a href="https://github.com/awslabs/aws-sam-cli">AWS SAM CLI</a> (which we’ll refer to as SAM local). This tool will emulate Lambda and API Gateway so you can interact with the application by hitting localhost:3000 rather than having to deploy to review every change.</p><p>To deploy our application we’ll be using <a href="https://serverless.com/">Serverless</a> which lets us deploy with a single command. Serverless makes it easy to define routes, path parameters, and environment vars to use in our live environment via the serverless.yml file.</p><h3>Project Structure</h3><p>API Gateway will relay HTTP request details to Lambda which will execute a single binary to process the incoming data and pass back a response. To satisfy this architecture, our web app will be 3 binary files that all import a common Go package. All of our authentication, business logic, and database models will be contained in the aptly named eventbus package.</p><p>This layout is very similar to the <a href="https://github.com/golang-standards/project-layout/tree/master/cmd/">Go CMD standard project layout</a> and for very complex web applications that is definitely a layout worth checking out. For the purpose of this project we will be organizing our binaries by their public facing paths and actions. endpoints/events/create/main.go will handle the POST /events route and will be compiled to bin/events/create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*6rknsW48-uNGfw1UIq7Ycw.png" /><figcaption>What we’ll have when all is said and done</figcaption></figure><h3>The eventbus Package</h3><h4>Database</h4><p>Data is love, data is life, nothing happens on the internet without data. Given this sage proverb I just came up with, let’s set up our database connection code in eventbus/database.go. We’ll be using <a href="https://github.com/jinzhu/gorm">Gorm</a>, a Go based Object Relation Manager, to handle database connection, models, queries, and migrations.</p><p>Create a new file, eventbus/database.go, and add the following code:</p><pre>package eventbus<br><br>import (<br>	&quot;os&quot;<br><br>	&quot;github.com/jinzhu/gorm&quot;<br>	_ &quot;github.com/jinzhu/gorm/dialects/postgres&quot;<br>)<br><br>var db *gorm.DB<br>var err error<br><br>func init() {<br>	db, err = gorm.Open(<br>		&quot;postgres&quot;,<br>		&quot;host=&quot;+os.Getenv(&quot;DATABASE_HOST&quot;)+<br>			&quot; user=&quot;+os.Getenv(&quot;DATABASE_USER&quot;)+<br>			&quot; dbname=&quot;+os.Getenv(&quot;DATABASE_NAME&quot;)+<br>			&quot; password=&quot;+os.Getenv(&quot;DATABASE_PASSWORD&quot;)+<br>			&quot; sslmode=disable&quot;+<br>			&quot; connect_timeout=5&quot;)<br><br>	if err != nil {<br>		panic(err)<br>	}<br><br>	db.LogMode(true)<br><br>	db.AutoMigrate(&amp;Event{})<br>	db.AutoMigrate(&amp;Subscription{})<br>}</pre><p>This is fairly straightforward. The init() function will be called when the application starts. We will be opening a connection to a PostgreSQL database and making it accessible for all other files in the eventbus package by storing it in the global variable db. The two db.AutoMigrate calls will create tables to accommodate our two primary structures. For the purpose of this article it will be assumed that we are working with a RDS PostgreSQL database.</p><p>Let’s start putting our database connection to use by building out the Subscription struct! If you recall, the Subscription structure will have an event_type field and an endpoint field which will both be strings. By adding gorm.Model to the Subscription structure columns for id, created_at, updated_at, and deleted_at will automatically be added to the subscriptions table. Since we’ll be querying for Subscriptions by event_type it makes sense to throw an index on that field.</p><p>Create a new file, eventbus/subscriptions.go, and add the following code:</p><pre>package eventbus<br><br>import (<br>	&quot;github.com/jinzhu/gorm&quot;<br>)<br><br>type Subscription struct {<br>	gorm.Model<br>	EventType string `json:&quot;event_type&quot; sql:&quot;index&quot;`<br>	Endpoint  string `json:&quot;endpoint&quot;`<br>}<br></pre><h4>Subscriptions</h4><p>Lookin’ sharp. Since we plan on supporting a route to create subscriptions and a route to delete subscriptions we should add functions to handle that. Both of these functions are straight forward.</p><p>CreateSubscription accepts two strings, eventType and endpoint, and will populate a new Subscription struct, insert it into the database, and return it.</p><p>DeleteSubscription will accept an id as a string, pull the record out of the database, delete it, and then return the subscription. In the case that the record was not found an empty Subscription struct will be returned.</p><p>Add the following code to eventbus/subscriptions.go.</p><pre>func CreateSubscription(eventType string, endpoint string) Subscription {<br>	subscription := Subscription{<br>		EventType: eventType,<br>		Endpoint:  endpoint,<br>	}<br><br>	db.Create(&amp;subscription)<br><br>	return subscription<br>}<br><br>func DeleteSubscription(id string) Subscription {<br>	var subscription Subscription<br>	db.First(&amp;subscription, id)<br>	db.Delete(&amp;subscription)<br>	return subscription<br>}</pre><h4>Events</h4><p>The counterpart to the Subscription struct will be our Event struct. An Event will consist of EventType and Payload both of which we will store as strings.</p><p>Create a new file, eventbus/events.go, and add the following code:</p><pre>package eventbus<br><br>import (<br>	&quot;github.com/jinzhu/gorm&quot;<br>)<br><br>type Event struct {<br>	gorm.Model<br>	EventType string `json:&quot;event_type&quot;`<br>	Payload   string `json:&quot;payload&quot;`<br>}</pre><p>Since we will only support a create route for events we’ll only need to add one additional function. The CreateEvent function will accept an event type and a payload, both as strings. These parameters will be used to populate a new Event struct which will then be saved in the database and returned.</p><p>Add the following code to eventbus/events.go.</p><pre>func CreateEvent(eventType string, payload string) Event {<br>	event := Event{<br>		EventType: eventType,<br>		Payload:   payload,<br>	}<br><br>	db.Create(&amp;event)<br>	startDeliveries(&amp;event)<br>	return event<br>}</pre><h4>Deliveries</h4><p>The discerning reader will notice that the startDeliveries, which is being called in the previous code block, has not been written yet. The primary functionality of an event bus is to deliver events to subscribers. As such, let’s add the business logic relaying the event data to all applicable subscribers.</p><p>Create a new file, eventbus/deliveries.go, and add the following code:</p><pre>package eventbus<br><br>import (<br>	&quot;bytes&quot;<br>	&quot;encoding/json&quot;<br>	&quot;fmt&quot;<br>	&quot;net/http&quot;<br>	&quot;time&quot;<br>)<br><br>func startDeliveries(event *Event) {<br>	var subscriptions []Subscription<br>	db.Where(&quot;event_type = ?&quot;, event.EventType).Find(&amp;subscriptions)<br><br>	for _, subscription := range subscriptions {<br>		deliverEvent(event, subscription.Endpoint)<br>	}<br>}<br><br>type Payload struct {<br>	Payload string `json:&quot;payload&quot;`<br>}<br><br>func deliverEvent(event *Event, path string) {<br>	payload := Payload{<br>		Payload: event.Payload,<br>	}<br>	data, _ := json.Marshal(payload)<br><br>	req, _ := http.NewRequest(&quot;POST&quot;, path, bytes.NewBuffer(data))<br>	req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br>	client := &amp;http.Client{<br>		Timeout: time.Second * 30,<br>	}<br><br>	resp, _ := client.Do(req)<br><br>	fmt.Println(resp)<br>}</pre><p>Our startDeliveries function, which accepts a pointer to an event, will query the database for all subscribers to the event’s type. We’ll then iterate over the subscriptions that were returned and pass the event and the subscription’s endpoint to the deliverEvent function.</p><p>The deliverEvent function will take the event’s payload string, pop it into a Payload struct, and post it to the subscription’s endpoint. To ensure our application doesn’t hang on non-responsive endpoints we’ll add a 30 second timeout when performing the outgoing request. Finally, the response will be printed so we can see what the endpoint responded with.</p><h4>Routing and Authentication</h4><p>With our business logic in place it’s time to start thinking about how we’ll manage incoming requests. As previously mentioned, I’ve found it helpful to use <a href="https://github.com/awslabs/aws-lambda-go-api-proxy">AWS Lambda Go Api Proxy</a> in conjunction with <a href="https://github.com/gin-gonic/gin">Gin</a> to handle incoming parameters, authentication, and rendering responses. When one of our Lambda functions is invoked we’ll create a global instance of a ginadapater.GinLambda and use it to handle all incoming requests from API Gateway. The ginadapter accepts a ginEngine which, to keep our code dry, we’ll build a factory for.</p><p>The three things our factory will need to build a gin.Engine for us are a path, a HTTP method, and the function we want to handle the request. The MountAuthorizedRoute function will initialize an engine, attach an authentication handler, and configure the engine use the path, HTTP method, and handler function we provide.</p><p>The authentication handler will check that the incoming request contains an Authentication header value that matches an environment variable. If the authentication token is missing an error will be returned saying that it is required. If the token is does not match we’ll return a message saying as much.</p><p>Create a new file, eventbus/routes.go, and add the following code:</p><pre>package eventbus<br><br>import (<br>	&quot;os&quot;<br><br>	&quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func MountAuthorizedRoute(path string, method string, fn gin.HandlerFunc) *gin.Engine {<br>	engine := buildEngine()<br>	group := engine.Group(&quot;/&quot;)<br>	group.Use(authorizedHandler())<br>	setMethodHandlerForGroup(method, path, fn, group)<br>	return engine<br>}<br><br>func buildEngine() *gin.Engine {<br>	engine := gin.New()<br>	engine.Use(gin.Logger())<br>	engine.Use(gin.Recovery())<br>	return engine<br>}<br><br>func setMethodHandlerForGroup(method string, path string, fn gin.HandlerFunc, group *gin.RouterGroup) {<br>	switch method {<br>	case &quot;post&quot;:<br>		{<br>			group.POST(path, fn)<br>		}<br>	case &quot;delete&quot;:<br>		{<br>			group.DELETE(path, fn)<br>		}<br>	}<br>}<br><br>func respondWithError(code int, message string, c *gin.Context) {<br>	resp := map[string]string{&quot;error&quot;: message}<br><br>	c.JSON(code, resp)<br>	c.Abort()<br>}<br><br>func authorizedHandler() gin.HandlerFunc {<br>	return func(c *gin.Context) {<br>		token := c.GetHeader(&quot;Authorization&quot;)<br><br>		if token == &quot;&quot; {<br>			respondWithError(401, &quot;Authorization token required&quot;, c)<br>			return<br>		}<br><br>		if token != os.Getenv(&quot;AUTHENTICATION_TOKEN&quot;) {<br>			respondWithError(401, &quot;Invalid Authorization token&quot;, c)<br>			return<br>		}<br><br>		c.Next()<br>	}<br>}</pre><p>Since this file does not use functionality from any other part of the eventbus package we could extract this into its own routing package; however, for the sake of maintaining simplicity I’ve opted to throw it in the eventbus package.</p><p>Give yourself a pat on the back — the core package that our lambda functions will be using is complete!</p><h3>Wiring Up Routes</h3><p>After all the work that went into creating our core package, building the API Gateway/Lambda handlers is going to seem anticlimactic. To reiterate, API Gateway will pass an incoming HTTP request to Lambda function that will execute a binary that can process the request and return a response. Since we’ll have 3 routes we’ll be building 3 separate applications that are all relatively small. The code for these apps will be in subfolders of endpoints/ in a single main.go file which will mount a route, handle requests, and return responses.</p><h4>Create Subscriptions</h4><p>The first endpoint app we’ll put together will handle requests to create new subscriptions. The main() function will bind the Handler function to be executed by all incoming Lambda calls. In turn, the Handler function will use the MountAuthorizedRoute function we defined in eventbus to mount our /subscriptions route to the processRequest function.</p><p>Create a new file, endpoints/subscriptions/create/main.go, and add the following code:</p><pre>package main<br><br>import (<br>	&quot;net/http&quot;<br><br>	&quot;github.com/aleccarper/serverless-eventbus/eventbus&quot;<br>	&quot;github.com/aws/aws-lambda-go/events&quot;<br>	&quot;github.com/aws/aws-lambda-go/lambda&quot;<br>	&quot;github.com/awslabs/aws-lambda-go-api-proxy/gin&quot;<br>	&quot;github.com/gin-gonic/gin&quot;<br>)<br><br>var initialized = false<br>var ginLambda *ginadapter.GinLambda<br><br>func Handler(req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {<br>	if !initialized {<br>		ginEngine := eventbus.MountAuthorizedRoute(&quot;/subscriptions&quot;, &quot;post&quot;, processRequest)<br>		ginLambda = ginadapter.New(ginEngine)<br>		initialized = true<br>	}<br>	return ginLambda.Proxy(req)<br>}<br><br>type Input struct {<br>	EventType string `form:&quot;event_type&quot; json:&quot;event_type&quot; binding:&quot;required&quot;`<br>	Endpoint  string `form:&quot;endpoint&quot; json:&quot;endpoint&quot; binding:&quot;required&quot;`<br>}<br><br>func processRequest(c *gin.Context) {<br>	var input Input<br>	c.BindJSON(&amp;input)<br>	subscription := eventbus.CreateSubscription(input.EventType, input.Endpoint)<br>	c.JSON(http.StatusCreated, subscription)<br>}<br><br>func main() {<br>	lambda.Start(Handler)<br>}</pre><p><em>For me, the import path is </em><em>github.com/aleccarper/serverless-eventbus/eventbus but you will need to change that to be the relative path to your </em><em>eventbus package.</em></p><p>When processRequest is executed it will be passed the incoming request information via a *gin.Context parameter. We’ll bind the incoming JSON to a new input struct and then pass the event_type and endpoint to the CreateSubscriptions function we created in the eventbus package.</p><p>After the subscription struct has been created and returned by CreateSubscriptions we’ll then return it, as JSON, back to the gin.Context with an HTTP status of 201.</p><h4>Delete Subscriptions</h4><p>The app that will handle deleting subscriptions will be almost identical to the create subscriptions app. Create a new file, endpoints/subscriptions/delete/main.go, and copy/paste the code we wrote for subscription creation. You can go ahead and delete the Input struct.</p><p>We’ll need to change the path and HTTP method used when mounting the ginEngine. Change:</p><pre>ginEngine := eventbus.MountAuthorizedRoute(&quot;/subscriptions&quot;, &quot;post&quot;, processRequest)</pre><p>to:</p><pre>ginEngine := eventbus.MountAuthorizedRoute(&quot;/subscriptions/:id&quot;, &quot;delete&quot;, processRequest)</pre><p>and update processRequest to:</p><pre>func processRequest(c *gin.Context) {<br>	subscription := eventbus.DeleteSubscription(c.Param(&quot;id&quot;))<br>	c.JSON(http.StatusOK, subscription)<br>}</pre><h4>Create Events</h4><p>The final app will handle creating events and it will also be almost identical to our previous two. Create a new file, endpoints/subscriptions/delete/main.go, and copy/paste the code we wrote for the subscription creation app.</p><p>We’ll need to change the path and HTTP method used when mounting the ginEngine. Change the mounting code to:</p><pre>ginEngine := eventbus.MountAuthorizedRoute(&quot;/events&quot;, &quot;post&quot;, processRequest)</pre><p>and update Input and processRequest to:</p><pre>type Input struct {<br>	EventType string `form:&quot;event_type&quot; json:&quot;event_type&quot; binding:&quot;required&quot;`<br>	Payload   string `form:&quot;payload&quot; json:&quot;payload&quot; binding:&quot;required&quot;`<br>}<br><br>func processRequest(c *gin.Context) {<br>	var input Input<br>	c.BindJSON(&amp;input)<br>	event := eventbus.CreateEvent(input.EventType, input.Payload)<br>	c.JSON(http.StatusCreated, event)<br>}</pre><p>And on that note we are done writing code! Let’s spin this bad boy up locally so we can test our event bus before we deploy it.</p><h3>Running our Event Bus Locally</h3><p>The AWS team has put together a fantastic tool for local development of Lambda/API Gateway applications called <a href="https://github.com/awslabs/aws-sam-cli">AWS SAM CLI</a>, and that’s we’ll be using.</p><p><em>At the time of this writing, there is a </em><a href="https://github.com/awslabs/aws-sam-cli/issues/389"><em>bug in the current release of the CLI that prevents Go binaries from being executed</em></a><em>. To avoid this you can install the previous version of the CLI via NPM by running </em>npm install -g aws-sam-local<em>.</em></p><h4>Configuring SAM CLI</h4><p>SAM consumes a config file that describes all of your lambda functions. You can use this file to match URLs to binaries and define other settings like environment variables.</p><p>Create a new file, template.yaml, and add the following code:</p><pre>AWSTemplateFormatVersion : &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31</pre><pre>Description: <br>  An example RESTful service<br>Resources:<br>  EventsCreate:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: main<br>      CodeUri: ./bin/events/create.zip<br>      Runtime: go1.x<br>      Timeout: 30<br>      Environment:<br>        Variables:<br>          DATABASE_USER:<br>          DATABASE_PASSWORD:<br>          DATABASE_HOST:<br>          DATABASE_NAME:<br>          AUTHENTICATION_TOKEN:<br>      Events:<br>        GetRates:<br>          Type: Api<br>          Properties:<br>            Path: /events<br>            Method: post<br>  SubscriptionsCreate:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: main<br>      CodeUri: ./bin/subscriptions/create.zip<br>      Runtime: go1.x<br>      Timeout: 30<br>      Environment:<br>        Variables:<br>          DATABASE_USER:<br>          DATABASE_PASSWORD:<br>          DATABASE_HOST:<br>          DATABASE_NAME:<br>          AUTHENTICATION_TOKEN:<br>      Events:<br>        GetRates:<br>          Type: Api<br>          Properties:<br>            Path: /subscriptions<br>            Method: post<br>  SubscriptionsDelete:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: main<br>      CodeUri: ./bin/subscriptions/delete.zip<br>      Runtime: go1.x<br>      Timeout: 30<br>      Environment:<br>        Variables:<br>          DATABASE_USER:<br>          DATABASE_PASSWORD:<br>          DATABASE_HOST:<br>          DATABASE_NAME:<br>          AUTHENTICATION_TOKEN:<br>      Events:<br>        GetRates:<br>          Type: Api<br>          Properties:<br>            Path: /subscriptions/{id}<br>            Method: delete</pre><h3>Environment Variables</h3><p>You’ll notice that the environment variables are blank in the config file — this is intentional as the you will want to commit the template file to your source control. Thankfully we can load environment variables from a env.json file dynamically when we start the SAM application. The env.json file can be added to .gitignore.</p><p>Create a new file, env.json, and add the following code:</p><pre>{<br>  &quot;EventsCreate&quot;: {<br>    &quot;AUTHENTICATION_TOKEN&quot;: &quot;lemme in&quot;,<br>    &quot;DATABASE_USER&quot;: &quot;mydatabaseuser&quot;,<br>    &quot;DATABASE_PASSWORD&quot;: &quot;mydatabasepassword&quot;,<br>    &quot;DATABASE_HOST&quot;: &quot;mydatabasehouse&quot;,<br>    &quot;DATABASE_NAME&quot;: &quot;mydatabasename&quot;<br>  },<br>  &quot;SubscriptionsCreate&quot;: {<br>    &quot;AUTHENTICATION_TOKEN&quot;: &quot;lemme in&quot;,<br>    &quot;DATABASE_USER&quot;: &quot;mydatabaseuser&quot;,<br>    &quot;DATABASE_PASSWORD&quot;: &quot;mydatabasepassword&quot;,<br>    &quot;DATABASE_HOST&quot;: &quot;mydatabasehouse&quot;,<br>    &quot;DATABASE_NAME&quot;: &quot;mydatabasename&quot;<br>  },<br>  &quot;SubscriptionsDelete&quot;: {<br>    &quot;AUTHENTICATION_TOKEN&quot;: &quot;lemme in&quot;,<br>    &quot;DATABASE_USER&quot;: &quot;mydatabaseuser&quot;,<br>    &quot;DATABASE_PASSWORD&quot;: &quot;mydatabasepassword&quot;,<br>    &quot;DATABASE_HOST&quot;: &quot;mydatabasehouse&quot;,<br>    &quot;DATABASE_NAME&quot;: &quot;mydatabasename&quot;<br>  }<br>}</pre><p>Change all of the database connection variables to match your RDS instance.</p><h3>Makefile</h3><p>Before we can start SAM we’ll need to build and zip our endpoint apps. The easiest way to do this is with a Makefile so we can simply run make at any time a change is made. Most IDEs also support executing a file, such as our makefile, every time a file is saved.</p><p>Create a new file, Makefile, and add the following code:</p><pre>build:<br>	dep ensure</pre><pre>	env GOOS=linux go build -ldflags=&quot;-s -w&quot; -o main endpoints/events/create/main.go<br>	mkdir -p bin/events<br>	zip bin/events/create.zip main<br>	mv main bin/events/create</pre><pre>	env GOOS=linux go build -ldflags=&quot;-s -w&quot; -o main endpoints/subscriptions/create/main.go<br>	mkdir -p bin/subscriptions<br>	zip bin/subscriptions/create.zip main<br>	mv main bin/subscriptions/create</pre><pre>	env GOOS=linux go build -ldflags=&quot;-s -w&quot; -o main endpoints/subscriptions/delete/main.go<br>	mkdir -p bin/subscriptions<br>	zip bin/subscriptions/delete.zip main<br>	mv main bin/subscriptions/delete</pre><p>Let’s break down these commands.</p><p>dep ensure will run Go’s package manager to download all missing packages we’re using. The dependencies will be saved in the vendor directory. dep is similar to bundler for those who are familiar with Ruby and hex for those have worked with Elixir.</p><p>After dep ensure there are 3 similar blocks — one for each of our endpoint applications. Each of these blocks will:</p><ul><li>Compile the source code in the main.go file and save it to the root project directory. Several options are passed to go build to ensure the file is executable under a linux environment, which is what both SAM and Lambda will be using. The binary is output to the root project as “main”.</li><li>The directory that we’ll use for matching binaries to URLs is then created.</li><li>We’ll then zip the endpoint binary and save it in our newly created directory. This zip file is used by SAM.</li><li>Finally the “main” binary is moved to the same directory and renamed. similiarThe binary is used by Serverless and deployed to AWS.</li></ul><h4>Starting SAM</h4><p>At long last we can finally build our serverless application and run it locally!</p><p>Run make &amp;&amp; sam local start-api --env-vars env.json to build our endpoint binaries and start the SAM local API Gateway service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2hXiqgIg8T_uGemZJ7U6Q.png" /><figcaption>Go SAM, go!</figcaption></figure><p>When SAM starts you will see that all 3 of our endpoints have been mounted and are accessible via localhost:3000. Using cURL we can hit these endpoints and verify their responses:</p><pre>curl -X POST \<br>  <a href="http://localhost:3000/subscriptions">http://localhost:3000/subscriptions</a> \<br>  -H &#39;Authorization: lemme in&#39; \<br>  -H &#39;Cache-Control: no-cache&#39; \<br>  -H &#39;Content-Type: application/json&#39; \  -d &#39;{<br>    &quot;event_type&quot;: &quot;new_user&quot;,<br>    &quot;endpoint&quot;: &quot;<a href="https://gewgle.com/">https://gewgle.com</a>&quot;<br>}&#39;</pre><pre>{&quot;ID&quot;:12,&quot;CreatedAt&quot;:&quot;2018-06-19T03:28:43.819217562Z&quot;,&quot;UpdatedAt&quot;:&quot;2018-06-19T03:28:43.819217562Z&quot;,&quot;DeletedAt&quot;:null,&quot;event_type&quot;:&quot;new_user&quot;,&quot;endpoint&quot;:&quot;<a href="https://gewgle.com/">https://gewgle.com</a>&quot;}</pre><pre>curl -X POST \<br>  <a href="http://localhost:3000/events">http://localhost:3000/events</a> \<br>  -H &#39;Authorization: lemme in&#39; \<br>  -H &#39;Cache-Control: no-cache&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;event_type&quot;: &quot;new_user&quot;,<br>    &quot;payload&quot;: &quot;<a href="/service/mailto:hwb@guvernment.gov">hwb@guvernment.gov</a>&quot;<br>}&#39;</pre><pre>{&quot;ID&quot;:22,&quot;CreatedAt&quot;:&quot;2018-06-19T03:20:20.530358392Z&quot;,&quot;UpdatedAt&quot;:&quot;2018-06-19T03:20:20.530358392Z&quot;,&quot;DeletedAt&quot;:null,&quot;event_type&quot;:&quot;new_user&quot;,&quot;payload&quot;:&quot;<a href="/service/mailto:hwb@guvernment.gov">hwb@guvernment.gov</a>&quot;}</pre><pre>curl -X DELETE \<br>  <a href="http://localhost:3000/subscriptions/11">http://localhost:3000/subscriptions/11</a> \<br>  -H &#39;Authorization: lemme in&#39; \<br>  -H &#39;Cache-Control: no-cache&#39; \<br>  -H &#39;Content-Type: application/json&#39;</pre><pre>{&quot;ID&quot;:12,&quot;CreatedAt&quot;:&quot;2018-06-19T03:28:43.819218Z&quot;,&quot;UpdatedAt&quot;:&quot;2018-06-19T03:28:43.819218Z&quot;,&quot;DeletedAt&quot;:null,&quot;event_type&quot;:&quot;new_user&quot;,&quot;endpoint&quot;:&quot;<a href="https://gewgle.com/">https://gewgle.com</a>&quot;}</pre><h3>Deploying</h3><p>Similar to SAM, Serverless, which is the service we’ll use to automate deploys, uses a config file to match binaries to URLs.</p><p>To avoid having environment variables in our config file we will first set our variables in AWS with Parameter Store. Use the following commands to set your environment variables:</p><pre>aws ssm put-parameter --name authentication --type String --value &quot;lemme in&quot;<br>aws ssm put-parameter --name database_user --type String --value mydatabaseuser<br>aws ssm put-parameter --name database_password --type String --value mydatabasepassword<br>aws ssm put-parameter --name database_host --type String --value mydatabasehost<br>aws ssm put-parameter --name database_name --type String --value mydatabasename</pre><p>Now that we have our env vars loaded we can put together the serverless config file.</p><p>Create a new file, serverless.yml, and add the following code:</p><pre>service: serverless-eventbus<br><br>provider:<br>  name: aws<br>  runtime: go1.x<br><br>package:<br> exclude:<br>   - ./**<br> include:<br>   - ./bin/**<br><br>functions:<br>  EventsCreate:<br>    handler: bin/events/create<br>    events:<br>      - http:<br>          path: /events<br>          method: post<br>    environment:<br>      AUTHENTICATION_TOKEN: ${ssm:authentication}<br>      DATABASE_USER: ${ssm:database_user}<br>      DATABASE_PASSWORD: ${ssm:database_password}<br>      DATABASE_HOST: ${ssm:database_host}<br>      DATABASE_NAME: ${ssm:database_name}<br>  SubscriptionsCreate:<br>    handler: bin/subscriptions/create<br>    events:<br>      - http:<br>          path: /subscriptions<br>          method: post<br>    environment:<br>      AUTHENTICATION_TOKEN: ${ssm:authentication}<br>      DATABASE_USER: ${ssm:database_user}<br>      DATABASE_PASSWORD: ${ssm:database_password}<br>      DATABASE_HOST: ${ssm:database_host}<br>      DATABASE_NAME: ${ssm:database_name}<br>  SubscriptionsDelete:<br>    handler: bin/subscriptions/delete<br>    events:<br>      - http:<br>          path: /subscriptions/{id}<br>          method: delete<br>    environment:<br>      AUTHENTICATION_TOKEN: ${ssm:authentication}<br>      DATABASE_USER: ${ssm:database_user}<br>      DATABASE_PASSWORD: ${ssm:database_password}<br>      DATABASE_HOST: ${ssm:database_host}<br>      DATABASE_NAME: ${ssm:database_name}</pre><p>With our environment variables set and the Serverless config file in place we can continue with the deploy.</p><p>Type in serverless deploy and you should get the following output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDevgHh5YxPAqbp-OE1QHQ.png" /><figcaption>Houston we have lift off</figcaption></figure><h3>Fin</h3><p>There ya go — a full fledged, serverless, web application. I hope this guide has helped tie the serverless API room together for you. If you have any questions or comments please just leave a note below!</p><p>Happen to enjoy writing awesome Ruby or Elixir code? <a href="https://www.taxjar.com/jobs/">Come work with me at TaxJar.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a76f7575751b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>