官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 杨浦区| 综艺| 色达县| 年辖:市辖区| 南澳县| 炎陵县| 大田县| 大田县| 仙居县| 探索| 邮箱| 宝丰县| 临沧市| 伊宁市| 莱西市| 孟连| 南郑县| 白水县| 南平市| 安乡县| 乌拉特中旗| 东乌珠穆沁旗| 虞城县| 清水河县| 都兰县| 玉田县| 禹城市| 浏阳市| 陕西省| 江油市| 达州市| 吕梁市| 广安市| 饶河县| 八宿县| 正定县| 衡东县| 偏关县| 平凉市| 龙南县| 许昌市|