Web Dev With Go

Web Dev With Go - Section 1

Basic Handler

package main

import (
"fmt"
"net/http"
)

func home(w http.ResponseWriter, r *http.Request) {

  fmt.Fprint(w, "<h1>Welcome to my site! </h1>")
}

func main() {

http.HandleFunc("/", home)
fmt.Println("Starting the server on :3000...")
http.ListenAndServe(":3000", nil)

}

Notes

  • func home receives two arguments:

    1. http.ResponseWriter
    2. *http.Request
  • The first parameter is an interface while the second one is a pointer.

  • It seems that the first one (http.ResponseWriter) is an interface since it is the response that the server will provide, so it could potentially be “whatever”, therefore an interface. Like that it is flexible.

  • The second one (*http.Request) is a pointer since it makes sense that we will not modify anything in the request.

  • “Registering” is called to the fact of associating the resource that is being queried, i.e “/” and the function that will define what we will do with the request and response. In our case, “func home”.

  • The function “home” follows the type HandlerFunc, which is described in the Go standard library.

 Share!

 
comments powered by Disqus