DEV Community

loading...
Debugg

Building a web server in Golang

faraazahmad profile image Syed Faraaz Ahmad ・1 min read

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() {

}

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)
}

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)
}

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))
}

Visit Debugg at https://debugg.me

Discussion

pic
Editor guide