DEV Community

Syed Faraaz Ahmad for Debugg

Posted on

3 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay