Skip to content

Web App

  • A handler in Golang acts as a controller in the common Model View Controller (MVC) pattern.
  • A router (or servemux in Go terminology) keeps the mapping between URL patterns and their handlers.
  • A web server, unlike in most other languages, for example Python you need something like Gunicorn or Uvicorn, Go can establish a web server and listen for incoming requests as part of the application itself.

New Project

mkdir ~/Golang/projects/newsfeeder && cd ~/Golang/projects/newsfeeder
go mod init newsfeeder.example.com

Getting Started

Create the following file:

main.go
package main

import (
    "log"
    "net/http"
)

func home(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("News Feeder"))
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", home)

    log.Print("starting server on :8080")

    err := http.ListenAndServe(":8080", mux)
    log.Fatal(err)
}

Run the application:

go run .

You will now see:

2024/06/21 14:14:18 starting server on :8080

And can visit http://localhost:8080/.