DEV Community

Syed Faraaz Ahmad for Debugg

Posted on

Building a web server in Golang

This post is a solution to the "Adam doesn't know routing" problem on Debugg. Visit Debugg at https://debugg.me

What we need here is a simple web server and one route, the / or "root" route, let's say.

There's a built-in package called net/http that can help us here. Open the main.go file, and import the package.

// main.go

package main

import "net/http"

func main() {

}

Enter fullscreen mode Exit fullscreen mode

The official documentation of the package shows an example for the function ListenAndServe, which is just what we need.

// main.go

...

func main() {
    http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

which will start an http server on port 8080. Now we need to return "Hello, world!" on the root route. For this we use a HandleFunc and pass it the route path and the handler function.

// main.go

...

func helloHandler(w http.ResponseWriter, _ *http.Request) {}

func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

to return "Hello, World!", we invoke io.WriteString by passing in the ResponseWriter instance and "Hello, World!".

The final file looks as follows

package main

import (
    "io"
    "log"
    "net/http"
)

func helloHandler(w http.ResponseWriter, _ *http.Request) {
    io.WriteString(w, "Hello, World!")
}

func main() {
    http.HandleFunc("/", helloHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Enter fullscreen mode Exit fullscreen mode

Visit Debugg at https://debugg.me

Top comments (0)