Article Image

Go

Creating a web server with Golang

Introduction

GO

In this tutorial, we will explore how to utilize Go's built-in HTTP package to create a simple and efficient web server. The server we will create will be capable of handling GET requests and serving static files, effectively acting as a file server. Additionally, we will demonstrate how to make the server respond to a POST request, which can be useful for processing data from a form submission, such as a contact form.

Setup

To proceed with this tutorial, it's necessary to have Go version 1.11 or a newer version installed. In this section, we will create the required files and set up the appropriate file structure. Then, we will import the necessary packages to test if everything is set up correctly. However, the setup for the Golang web server is straightforward, so there's no need to worry about complexity.

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

To write code for the server, you need to open the server.go file and import the necessary packages. We will use fmt package to print helpful information to the terminal and log package to print critical errors if 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"
 )

Finally, we will add a basic main() function to the server.go file, which will print a message to the terminal.

func main() {
  fmt.Printf("Starting server at port 3000\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 3000

Starting a web server with GET routes

At this point, we'll build a web server that can reply to incoming GET requests and is truly accessible on port 3000.

Change the main() function's code to launch a web server on port 3000. The http packet we loaded in step one exports the ListenAndServe function. With this method, we can launch the web server and choose the port that will be used to receive incoming requests.

Keep in mind that the port argument must be given as a string with a colon before any punctuation. The second option accepts a handler to set up HTTP/2 on the server. For the sake of this tutorial, this is unimportant, therefore we can safely supply nil as the second argument.

 func main() {
    fmt.Printf("Starting server at port 3000\n")
    if err := http.ListenAndServe(":3000", nil); err != nil {
        log.Fatal(err)
    }
}

At this point, the server can start, but it still doesn’t know how to handle requests. We need to pass handlers to the server so it knows how to respond to incoming requests and which requests to accept.

We’ll use the HandleFunc function to add route handlers to the web server. The first argument accepts the path it needs to listen for /hello. Here, you tell the server to listen for any incoming requests for http://localhost:3000/go. The second argument accepts a function that holds the business logic to correctly respond to the request.

By default, this function accepts a ResponseWriter to send a response back and a Request object that provides more information about the request itself. For example, you can access information about the sent headers, which can be useful for authenticating the request.

func main() {
    http.HandleFunc("/go", func(w http.ResponseWriter, r *http.Request){
        fmt.Fprintf(w, "Go Language!")
    })


    fmt.Printf("Starting server at port 3000\n")
    if err := http.ListenAndServe(":3000", nil); err != nil {
        log.Fatal(err)
    }
}

As you can see, the handler sends a Go Language message as we pass this response to the ResponseWriter.

Let's now test out this arrangement. Use go run server to launch the web server. Visit http://localhost:3000/go right away. You can move on to the following phase, where you'll learn how to add fundamental security to your Golang web server routes, if the server replies with Go Language.

Thanks for reading!!!

SerinaPokharel

Author