How to Create a Go (Golang) API on Google App Engine

How to Create a Go (Golang) API on Google App Engine

Learn how to create an API with a Server, written in Go, to deploy to Google App Engine. Google App Engine is Platform as a Service (PaaS). App Engine allows you to build scalable web and mobile back-ends with traffic splitting and firewall capabilities.

Why Google App Engine?

Google App Engine is Platform as a Service (PaaS). It aims to make deployment easier. It is fully managed, pay-as-you-go, high availability, it ensures a fast time to market, and supports a wide variety of programming languages.

App Engine allows you to build scalable web and mobile back-ends with traffic splitting and firewall capabilities.

Standard vs Flexible Environment

You have two options when creating an App Engine environment:

  • Standard — Applications run in a sandbox. Choose this if you need rapid scaling or you experience dramatic and unexpected spikes of traffic
  • Flexible — Instancesrun within Docker containers on Compute Engine virtual machines. Choose this if you have consistent traffic, need to scale up or down, or access resources on the Compute Engine.

It’s important to note that the App Engine Application URL will be named based on the project name. So take this into account when choosing your cloud project.

Let’s get started!

1) Setting up App Engine in Cloud Console

Firstly, let’s set up the App Engine Project.

Go to https://console.cloud.google.com/appengine.

After some automatic initialization, you should be greeted with this screen…

Image for post

The App Engine Welcome Screen

Click ‘Get Started

Image for post

App Engine Configuration Options

Choose ‘Go’ from the dropdown.

We’ll be using the standard environment for this example.

The next steps are to download the SDK

This gives you access to the command line tools (CLI).

Initialize the project

Using the gcloud command, initialize the project.

$ gcloud init

Until you’ve deployed your application to the app engine, your dashboard will look like this.

Image for post

Temporary Screen Until Deployed to App Engine

So now that the app engine is all setup, it’s time to actually write our server.

2) Write a simple Server application in Go

We’ll be using the Go version 1.14. We’ll also be using Go modules.

There are 3 files that are essential to our application. These are outlined below.

Runtime Config — app.yaml

The first file that we need to create is the app.yaml file. This file is mandatory in an app engine project.

runtime: go114

app.yaml file for App Engine Runtime

Go Module — go.mod

We also need to create our Go module.

module server

go 1.14

Go module file

Main File — main.go

Firstly, we need to create a function in the main file that grabs the port number. It’s just a function that just gets the appropriate port number that our API is listening on based on the current environment.

We use the os library to get the port (if it is an environment variable), default to port 8080 if the environment variable isn’t set, and return the port number to the caller as a string.

func getPort() string {
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
        log.Printf("Defaulting to port %s", port)
    }
    return port
}

Get and Set the port number

Initialize our HTTP server client

Let’s create our simple HTTP server to listen to requests.

Firstly we’ll get the port using our getPort() function we created previously.

We’ll then write our anonymous handler function to handle requests and deal with the response.

Our API doesn’t do anything yet, so it’s pretty useless. But we’ll soon start handling some parameters like you would in an actual API.

Then we’ll call the function that instructs our HTTP client to listen and serve our application on the specified port with http.ListenAndServe , while catching any errors that might arise.

package main
import (
  "fmt"
    "log"
    "net/http"
  "os"
       )

func getPort() string {

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
        log.Printf("Defaulting to port %s", port)
    }
    return port

}

func main() {

    port := getPort()
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            // do something
    })
    //  Start HTTP
    if err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil); err != nil {
        log.Fatal("Failed starting http server: ", err)
    }

}

golang programming api go developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Build a Go Web API with the New Digital Ocean App Platform: A How-To Guide

Recently, Digital Ocean announced they're entering the PaaS market with their new application platform. They've hosted virtual machines (droplets) and Kubernetes based services for years, but now they're creating a platform that's a simple point and click to get an application up and running.

Golang Web Development:Th Best Programming Language in 2020

Golang Web Development is the new trend globally. Get all the details about the Golang development here. Hire Golang Developers.

A Simple Guide to API Development Tools

APIs can be as simple as 1 endpoint for use by 100s of users or as complex as the AWS APIs with 1000s of endpoints and 100s of thousands of users. Building them can mean spending a couple of hours using a low-code platform or months of work using a multitude of tools. Hosting them can be as simple as using one platform that does everything we need or as complex as setting up and managing ingress control, security, caching, failover, metrics, scaling.

Tracking a Developer’s Journey From Documentation Visit

Measuring website activity provides only half the story. See how to best track the developer's journey and what funnel stages makes sense for API-first products

How to Market to Developers with Paid Marketing

Selling to developers is hard. How to market to developers efficiently using paid advertising leveraging inbound marketing techniques.