Understanding Go's net/http package
Go's net/http
 package deals with HTTP client and server implementations. Here, we are mainly interested in the server implementation. Let us create a small Go program called basicHandler.go
that defines the route and a function handler:
package main import ( "io" "net/http" "log" ) // hello world, the web server func MyServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n") } func main() { http.HandleFunc("/hello", MyServer) log.Fatal(http.ListenAndServe(":8000", nil)) }
This code does the following things:Â
- Create a route called Â
/hello
. - Create a handler called
MyServer
. - Whenever the request comes on the route (
/hello
), the handler function will be executed. - Write
hello, world
to the response. - Start the server on port
8000
.ListenAndServe
returnserror
 if something goes wrong. So log it usinglog.Fatal
. - TheÂ
http
package has a function calledHandleFunc
, using which we can map an URL to a function.
- Here,...