How it works…

Once we run the program, the HTTP server will start locally listening on port 8080.

Execute a GET request from the command line, as follows:

$ curl -X GET -i http://localhost:8080/

This will log the request details in the server log in the Apache Common Log Format, as shown in the following screenshot:

We could also execute http://localhost:8080/hello/foo from the command line, as follows:

$ curl -X GET -i http://localhost:8080/hello/foo

This will log the request details in the server.log in the Apache Combined Log Format, as shown in the following screenshot:

Let's understand what we have done in this recipe:

  1. Firstly, we imported two additional packages, one is os, which we use to open a file. The other one is github.com/gorilla/handlers, which we use to import logging handlers for logging HTTP requests, as follows:
import ( "net/http" "os" "github.com/gorilla/handlers" "github.com/gorilla/mux" )
  1. Next, we modified the main() method. Using router.Handle("/", handlers.LoggingHandler(os.Stdout,
    http.HandlerFunc(GetRequestHandler))).Methods("GET"), we wrapped GetRequestHandler with a Gorilla logging handler, and passed a standard output stream as a writer to it, which means we are simply asking to log every request with the URL path / on the console in Apache Common Log Format.
  2. Next, we create a new file named server.log in write-only mode, or we open it, if it already exists. If there is any error, then log it and exit with a status code of 1, as follows:
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
  1. Using router.Handle("/post", handlers.LoggingHandler(logFile, PostRequestHandler)).Methods("POST"), we wrapped GetRequestHandler with a Gorilla logging handler and passed the file as a writer to it, which means we are simply asking to log every request with the URL path /post in a file named /hello/{name} in Apache Common Log Format.
  2. Using router.Handle("/hello/{name}", handlers.CombinedLoggingHandler(logFile, PathVariableHandler)).Methods("GET"), we wrapped GetRequestHandler with a Gorilla logging handler and passed the file as a writer to it, which means we are simply asking to log every request with the URL path /hello/{name} in a file named server.log in Apache Combined Log Format.
..................Content has been hidden....................

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