Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
http
web server

How to make an HTTP server in Go

Educative Answers Team

In this shot, we will use the standard net/http package to make a simple HTTP web server.

svg viewer

Implementation

We will be writing an HTTP web server that listens on the port 8080. The net/http package provides the function ListenAndServe. The first argument is the port number and the second is the handler, which is mainly used for HTTP/2 servers. However, we won’t be using this parameter in this shot, so we pass nil for the default router:

func main() {
    http.ListenAndServe(":8080", nil)
}

Next, we will add a handler. A handler is a function that implements the http.Handler interface – the handler takes an http.ResponseWriter and an http.Request as arguments.

Our hello handler responds using the http.ResponseWriter w with a, “Hello from the server!” message:

func hello(w http.ResponseWriter, req *http.Request) {

    fmt.Fprintf(w, "Hello from the server!\n")
}

We finally register our hello handler on the server routes using the http.HandleFunc function, which sets up the default router in the net/http package and takes a function as an argument.

http.HandleFunc("/hello", hello)

Once all the pieces are put together, we will get the following HTTP server in Go.
package main
import (
    "fmt"
    "net/http"
)

// A handler for "/hello" route
func hello(w http.ResponseWriter, req *http.Request) {

    fmt.Fprintf(w, "Hello from the server!\n")
}

func main() {

    // Registering the hello handler
    http.HandleFunc("/hello", hello)

    // Listening on port 8080
    http.ListenAndServe(":8080", nil)
}

You can run the server on localhost. Accessing localhost:8080/hello route will return the response "Hello from the server!\n", as expected.

RELATED TAGS

golang
go
http
web server
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring