Part 1

Start with making a folder for our code, in this folder create a file named main.go

Open main.go and put the following in it:


package main

import (
  "log"
  "net/http"

  "time"
)

func main() {
  s := &http.Server{
    ReadTimeout:  60 * time.Second,
    WriteTimeout: 60 * time.Second,
    Addr:         ":8080",
  }
  log.Println("Listening on port 8080")
  err := s.ListenAndServe()
  if err != nil {
    log.Fatal("ListenAndServe: ", err)
  }
}

Now if we type go run main.go and visit localhost:8080 we get a 404, let's do something about it but first, why are we listening on 8080 instead of 80 which is default for http? To run directly on port 80 requires root access so when we deploy we can choose to either change the port to 80 and run with sudo or redirect traffic from port 80 (or 443 if we have https) to 8080, for example with iptables: sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

Note that the iptables command has to be rerun on server restart.

In func main add the line
http.HandleFunc("/ip", serveIP)
above the server declaration. Then above the main func add the function
func serveIP(w http.ResponseWriter, r *http.Request){
  fmt.Fprintf(w, "RemoteAddr: "+r.RemoteAddr)
}

Note that we also have to add fmt to our imports. Now if we visit localhost:8080/ip it will print our ip, neat!

Instead of using the built in routing system we will use a more advanced one from Gorilla called mux , so go ahead and
go get github.com/gorilla/mux

Next add the function
func serveHome(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello from home!")
}
and in the main func add
router := mux.NewRouter()
router.HandleFunc("/", serveHome)
http.Handle("/", router)
Also don't forget to import mux.

So why mux? What does it bring to the table? Enter keyword routes! Add the following line:
router.HandleFunc("/greet/{name}", serveGreet)
And the following function:
func serveGreet(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  fmt.Fprintf(w, "Hello "+vars["name"])
}
Now if we go to localhost/greet/anonymous it will say Hello anonymous!

Alright! Now we have the tools needed to build an API server. Follow along in part two as we add templates to serve html pages.

The full code of main.go can be viewed here: https://github.com/jhlq/gocourse/blob/main/part1/main.go




Updated on 2020-11-30.