Golang is a great language for creating simple yet efficient web servers and web services. It provides a built-in HTTP package that contains utilities for quickly creating a web or file server.

The goal of this tutorial is to create a web server that can accept a GET request and serve a response. We’ll use the server to serve static files, acting as a file server. We’ll then make the web server respond to a POST request coming from a form submission, such as a contact form.

Without further ado, let’s explore how to build your first web server with Golang.

Setup

You’ll need Go version 1.11 or higher to follow this tutorial.

In this section, we’ll create all the necessary files and establish the correct file structure. After that, we’ll import our packages to test whether the setup works. Don’t worry — the setup is very basic for the Golang web server.

Create the following files and folders according to the structure below. The file server.go sits at the root of your project, as does the static folder, which contains two HTML files: index.html and form.html.

- server.go
- static/
- - index.html
- - form.html

Now let’s write some code. Open the server.go file and import the required packages. We’ll use fmt to print useful data to the terminal and log to print fatal errors in case the web server crashes.

The net/http is the most important package. It provides all the functionality for creating an HTTP client or server implementation such as a Golang web server.

package main

import (
    "fmt"
    "log"
    "net/http"
)

Lastly, let’s add a simple main() function in the server.go file that prints a message to the terminal.

func main() {
    fmt.Printf("Starting server at port 8080\n")
}

To test the setup, start the fictive server with the following command.

go run server.go

If you followed along with the setup, you should see the following output in your terminal.

Starting server at port 8080

If all looks good, the next step is to create a web server.

#go #golang #web-service #developer #web-development

How to Build Your First Web Server with Golang
27.65 GEEK