A simple web server

Go provides us with an inbuilt library for building web servers, net/http. For every endpoint we want to create on our server, we have to do two things:

  1. Create a handler function for the endpoint, which accepts two parameters, one for writing to response and one to handle the incoming Request.
  2. Register the endpoint using net/http.HandleFunc.

The following is a simple web server that accepts all incoming requests, logs them on to the console, and then returns a Hello, World! message.

// helloServer.go 
 
package main 
 
import ( 
    "fmt" 
    "log" 
    "net/http" 
) 
 
func helloWorldHandler(w http.ResponseWriter, r *http.Request) { 
    msg := fmt.Sprintf("Received request [%s] for path: [%s]", r.Method, r.URL.Path) 
    log.Println(msg) 
 
    response := fmt.Sprintf("Hello, World! at Path: %s", r.URL.Path) 
    fmt.Fprintf(w, response) 
} 
 
func main() { 
    http.HandleFunc("/", helloWorldHandler) // Catch all Path 
 
    log.Println("Starting server at port :8080...") 
    http.ListenAndServe(":8080", nil) 
} 

Here are some sample requests and responses when requesting the URL in the browser:

http://localhost:8080/  --> Hello, World! at Path: / 
http://localhost:8080/asdf  htt--> Hello, World! at Path: /asdf 
http://localhost:8080/some-path/123  --> Hello, World! at Path: /some-path/123 

And the following is the server output:

2017/10/03 13:35:46 Starting server at port :8080... 
2017/10/03 13:36:01 Received request [GET] for path: [/] 
2017/10/03 13:37:22 Received request [GET] for path: [/asdf] 
2017/10/03 13:37:40 Received request [GET] for path: [/some-path/123] 

Notice that even though we have provided multiple paths, they are all defaulting to the / path.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.8.8