LanguagesWeb Development with Go (Golang)

Web Development with Go (Golang) content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The Go language has excellent built-in support for web development and web app programming. There are packages to work with the generic functionalities for implementing networking and Internet protocols, making it easy to use functionality like the Google App engine. In this Go programming tutorial, we introduce some of the features of the Golang standard library that allow us to write code that seamlessly integrates with the web and can be used for creating websites and web applications.

How Does the Web Work?

Before we start learning the ins and outs of Go web development, let’s quickly detour and take a look at how the web actually works. The web – and networks in general – always works using the client-server principle. The client is a computer that requests a service via a URL and the server is a computer (or server) that serves the request. The URL (Uniform Resource Locator) is the address that decides which server the client wants to request service from.

In this process, the server usually responds back in the form of a web page, which the client displays in the browser. Therefore, for a normal user, any URL entered in the browser fetches a web page from some server. What actually happens is that, after you type the URL, the host part of the URL is sent to the DNS (Domain Name Server), which maps to the IP (Internet Protocol) address of the host.

Once the IP address is obtained, a TCP (Transmission Control Protocol) connection is set up. Understand that all of this “play” of Internet browsing (client request-server response) is defined by HTTP (HyperText Transfer Protocol) and the server that facilitates this is called an HTTP or web server. TCP/IP contains several protocols for different purposes, such as SMTP for Email service, FTP for file service, HTTP for web service, and so on.

Web Development in Go

Therefore, the browser sends HTTP requests through a TCP connection, and the server that receives the request, processes or handles it and replies back with an HTTP response. The HTTP response contains the code that makes up the web page. The browser renders the page according to the received code and then disconnects from the server.

Note that the DNS (Domain Name System) is the naming system for computer network services responsible for converting domain names to actual IP addresses.

Read: Intro to Socket Programming in Go

What Is Web Programming and Web Development?

To continue upon the above train of thought, the browser renders a page upon receiving the HTTP response from the server. The response consists of code, typically written in web development languages and scripting languages such as HTML, CSS, and JavaScript. HTML is responsible for constructing the page document, structure, and layout. CSS leverages the look and feel. JavaScript is also used to enhance the functionality of the web page and makes browsing more convenient for the end-user. The request sent from the HTTP client is processed by the server. This processing part is written in one or many server languages such as PHP, Java, C++, Golang, and so forth. Sometimes the processing server also requires a backend database. In that event, database access-specific code is also written, typically using the same language or a language that extends the primary programming language. Web development, therefore, includes writing code in one or all of these web development languages.

Web Development in Go and Golang

The Go programming language is one of the many high-level languages that can be used for web development. The criteria for choosing any one of them can include performance, convenience, learning curve, available libraries, and any other number of considerations. Although the end result is the same, the decisive factor is how quickly and conveniently we can create a web application. PHP, Java, and C# are all excellent and proven in this field. The standard library support of Go, however, makes web development particularly easy, convenient, and quick.

With Golang, web developers simply need the Go compiler and nothing else to get started developing web pages and web apps. The built-in features of Go already include a web server and the net/http package in the standard library, which provides the necessary functions required for working with the HTTP protocol. The HTTP client and HTTP server are part of this library. This makes web programming (at least to begin with ) hassle-free and quick. However, as you dive deeper, there are many twists and turns in web development where we have to use other libraries, languages, and even web frameworks, as well.

Read: Working with XML Files in Go

The Go Web Server

The stub web server of the net/http package delegates the handling of requests in our code. It follows the following four basic principles:

  • Request: user data request using POST, GET, COOKIE, and URL.
  • Response: response back to the client.
  • Connection: establish a TCP connection between the client and server.
  • Handler: processing of the request received (also business logic).

Web Development in Golang

Once the web server is up, it creates a listening socket at the specific port and waits for the connection request from the client. The process includes:

  • Listening socket is created and waits for client connection.
  • Accepts requests received from the client.
  • Process request: reads the HTTP header and checks if it is a POST method. Reads the message and passes it to the handler for processing and finally responds back to the client.

Go Web Server Example Code

Let us write some simple and minimal code to illustrate how to create a web server in Go. We will assume the Go compiler is installed properly on your system. Type the following (Linux) commands to begin:

$ mkdir webprojects
$ mkdir webprojects/project1
$ cd webprojects/project1
$ nano main.go

If you are using the Visual Code IDE, replace:

$ nano main.go 


$ code main.go

Next, type the following Go code to create the web server:

package main
import (
func greetHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Welcome to my home page</h1>")
fmt.Fprintf(w, "Requested URL path = %s", r.URL.Path)
func main() {
http.HandleFunc("/", greetHandler)
fmt.Println("Starting server at port 9999...")
http.ListenAndServe(":9999", nil)
$ go run main.go

The server should start running. Open the browser and type the following into the address bar: http://localhost:9999, followed by pressing Enter. The browser should keep running. To stop it, just press Ctrl+C.

Read: Working with JSON Files in Go

Understanding the Go Web Server Code

ResponseWriter implements the io.Writer interface; as a result, it can be used with the functions from the fmt package. We can embed HTML code and print them in the client area of the browser using http.ResponseWriter.

The function HandleFunc registers the handler function named greetHandler for the given pattern in the defaultServeMux used by the server. ServeMux is the HTTP request multiplexer responsible for matching the incoming request against the registered pattern and calls the appropriate handler for the pattern. In our case the pattern is given “/”, which means a request to the URL http://localhost:9999 will be handled by the greetHandler function.

Add another handler, such as the thanksHandler function, as follows:

func thanksHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Thanks. Visit again.</h1>")

Next, register this handler as well with func main:

func main() {
http.HandleFunc("/", greetHandler)
http.HandleFunc("/thanks", thanksHandler)
fmt.Println("Starting server at port 9999...")
http.ListenAndServe(":9999", nil)

Next, register this handler as well with func main:

func main() {
http.HandleFunc("/", greetHandler)
http.HandleFunc("/thanks", thanksHandler)
fmt.Println("Starting server at port 9999...")
http.ListenAndServe(":9999", nil)

Now, as you type the URL http://localhost:9999/thanks, this will invoke the thanksHandler.

The ListenAndServe listens on the TCP network address and then calls Serve with a handler to handle requests on incoming connections. Here the address value indicates the port number that the server will keep listening to for any incoming client request. The handler is typically nil, in which case the default ServeMux is used.

Final Thoughts on Go Web Development

The Golang creators are stalwarts in web technology, hence it is no surprise that the language has excellent standard library support for the Internet. For example, the textproto package implements generic support for text-based request-response protocols like HTTP, NNTP, and SMTP. Here, we have only touched the tip of the iceberg. Even the http package has a lot of other functionalities, which we will explore in future Golang web development tutorials.

Read more Go and Golang programming tutorials.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories