In this article, I’ll teach you how to create simple web servers with the Go language.
Getting Started With Golang
It would be best if you have Go installed on your device (which can be a Windows, Mac, or Linux device). Before you start to write Go code, you need to create a new directory to store your files in:
$ mkdir newserver
$ cd newserver
In this folder, you create your main application file, main.go
:
package main
import (
"fmt"
)
We import the fmt package from the standard Go library. We will need this in the future.
Hello World Example
We are going to start with a basic example of a web server. You need to add the following import
to your code:
import (
"fmt"
"net/http"
)
Registering a Request Handler
First, create a handler that receives all incoming HTTP connections from browsers, HTTP clients, or API requests. A handler in Go is a function with this signature:
func (w http.ResponseWriter, r *http.Request)
This function takes two arguments:
- An
http.ResponseWriter
, which is where you write your text/HTML response. - An
http.Request
that contains all information about this HTTP request, including things like the URL and header fields.
To register the request handler, we use:
http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Medium, you've requested: %s\n", r.URL.Path)
})
Ports
We need to add a port to make a web server listen to a specific address and port:
http.ListenAndServe(":80", nil)
Static Assets
To serve static assets like JavaScript, CSS, and images, we use the built-in http.FileServer
:
fs := http.FileServer(http.Dir("static/"))
Once our file server is in place, we just need to point a URL path at it:
http.Handle("/static/", http.StripPrefix("/static/", fs))
Routing
One thing Go doesn’t do very well is complex request routing (like segmenting a request URL into single parameters). Fortunately, there is a very popular package for this called gorilla/mux. It is well known in the Go community for its good code quality.
Install the package
Installing this package in Go is very simple:
go get -u github.com/gorilla/mux
Create a new router
First, create a new request router. The router is the main router for your web application and will later be passed as a parameter to the server:
r := mux.NewRouter()
URL parameters
With this package, it’s very easy to use URL parameters. It looks like this:
r.HandleFunc("/user/{username}", func(w http.ResponseWriter, r *http.Request) {
//Route code})
Define the type of request
You can easily define your type of request (for example, a GET or POST request) by adding the following line of code:
r.HandleFunc("/user/{username}", func(w http.ResponseWriter, r *http.Request) {
//Route code}).Methods("GET")
Register the router
When you have set up your router, you need to register it to make it work:
http.ListenAndServe(":80", r)
HTML Templates
When building a web server (unless you are building a REST API), you want to use HTML pages to display your data. Therefore, you need to import a new package:
import ( "html/template" "net/http" )
When you have built your own HTML page, you can put it in your templates
folder. Then add the following code to your main func
:
func main() {
tmpl := template.Must(template.ParseFiles("layout.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w)
})
http.ListenAndServe(":80", nil)
}
This will load your HTML template into your web server’s route.
Conclusion
I hope you learned a lot from this beginner’s guide to web servers in Go. You learned the fundamentals of web programming for Go, so you should now be able to figure out new things and continue along on your own web development journey!