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

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.
主站蜘蛛池模板: 清河县| 镇坪县| 万年县| 鱼台县| 田阳县| 黔江区| 蛟河市| 永新县| 定安县| 石嘴山市| 调兵山市| 建阳市| 炉霍县| 加查县| 乐清市| 资阳市| 白朗县| 永胜县| 盐津县| 两当县| 黔西县| 连城县| 武邑县| 延吉市| 渝北区| 冕宁县| 新津县| 陈巴尔虎旗| 德州市| 横峰县| 温宿县| 博爱县| 高淳县| 黔西| 伊川县| 武平县| 靖远县| 株洲市| 济源市| 阿拉善左旗| 台东县|