Home > Articles

Creating HTTP Servers with the Go Programming Language

  • Print
  • + Share This
Learn how to create web servers that can respond to different routes, different types of requests, and different content types in Go.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

This chapter is from the book

Go offers strong support for creating web servers that can serve web pages, web services, and files. During this hour, you will learn how to create web servers that can respond to different routes, different types of requests, and different content types. By taking advantage of Go’s approach to concurrency, writing web servers in Go is a great option.

Announcing Your Presence with the “Hello World” Web Server

The net/http standard library package provides multiple methods for creating HTTP servers, and comes with a basic router. It is traditional to create a Hello World program to announce a basic presence to the world. The most basic HTTP server in Go is shown in Listing 18.1.

LISTING 18.1 Basic HTTP Server in Go

 1:  package main
 3:  import (
 4:      "net/http"
 5:  )
 7:  func helloWorld(w http.ResponseWriter, r *http.Request) {
 8:      w.Write([]byte("Hello World\n"))
 9:  }
11:  func main() {
12:      http.HandleFunc("/", helloWorld)
13:      http.ListenAndServe(":8000", nil)
14:  }

Although the program is just 14 lines, plenty is going on.

  • The net/http package is imported.

  • Within the main function, a route / is created using the HandleFunc method. This takes a pattern describing a path, followed by a function that defines how to respond to a request to that path.

  • The helloWorld function takes a http.ResponseWriter and a pointer to the request. This means that within the function, the request can be examined or manipulated before returning a response to the client. In this case, the Write method is used to write the response. This writes the HTTP response including status, headers, and the body. The usage of []byte initializes a byte slice and converts the string value into bytes. This means it can be used by the Write method, which expects a slice of bytes.

  • The ListenAndServe method is used to start a server to respond to a client that listens on localhost and port 8000.

Although this is a short example, if you can begin to understand how a web server operates in Go, you will be well on your way to creating more complex programs.

  • + Share This
  • 🔖 Save To Your Account