Deploy a Go/Golang Web App to Heroku

#go #golang #webdevelopment #web #backend

Ankit Sharma Dec 17 2020 · 1 min read
Share this

This article covers creating a basic web server written in Go with an end-point returning a JSON response

Download Go 

Create a file in your directory :  server.go

Copy and paste the code given below

package main

import (

type Profile struct {
  Name    string
  Hobbies []string

func main() {
  http.HandleFunc("/", myJson)
  fmt.Printf("Starting server at port 8080\n")
  port := os.Getenv("PORT")

  if len(port) == 0 {
	port = "8080"

  if err := http.ListenAndServe(":"+port, nil); err != nil {

func myJson(w http.ResponseWriter, r *http.Request) {
  profile := Profile{"Alex", []string{"snowboarding", "programming"}}

  js, err := json.Marshal(profile)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)

  w.Header().Set("Content-Type", "application/json")

To start the server use the following command 

go run server.go

Open your browser and go to the URL : http://localhost:8080

JSON response

  Let's make the current directory the root of a module by using 

go mod init server

The go mod vendor command constructs a directory named vendor in the main module's root directory that contains copies of all packages needed to support builds and tests of packages in the main module. Packages that are only imported by tests of packages outside the main module are not included. As with go mod tidy and other module commands, build constraints except for ignore are not considered when constructing the vendor directory.

go mod vendor

A new mod file named go.mod will be created in the working directory

Initialize a Git Repository

git init
git add .


git commit -m "lets go"

Login using Heroku CLI  : Download

heroku login

After logging in create a new app using the below command

heroku create

Push and done.

git push heroku master

See the demo here

Follow me on linkedin for any queries :-  Ankit Sharma | LinkedIn

Read next