- Go Web Development Cookbook
- Arpit Aggarwal
- 163字
- 2021-08-27 19:01:15
How to do it…
Let's implement logging using Gorilla handlers. Perform the following steps:
- Install the github.com/gorilla/handler and github.com/gorilla/mux packages using the go get command, as follows:
$ go get github.com/gorilla/handlers
$ go get github.com/gorilla/mux
- Create http-server-request-logging.go and copy the following content:
package main
import
(
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
var GetRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("Hello World!"))
}
)
var PostRequestHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
w.Write([]byte("It's a Post Request!"))
}
)
var PathVariableHandler = http.HandlerFunc
(
func(w http.ResponseWriter, r *http.Request)
{
vars := mux.Vars(r)
name := vars["name"]
w.Write([]byte("Hi " + name))
}
)
func main()
{
router := mux.NewRouter()
router.Handle("/", handlers.LoggingHandler(os.Stdout,
http.HandlerFunc(GetRequestHandler))).Methods("GET")
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
}
router.Handle("/post", handlers.LoggingHandler(logFile,
PostRequestHandler)).Methods("POST")
router.Handle("/hello/{name}",
handlers.CombinedLoggingHandler(logFile,
PathVariableHandler)).Methods("GET")
http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
}
- Run the program, using the following command:
$ go run http-server-request-logging.go
推薦閱讀
- Mastering Machine Learning for Penetration Testing
- 物聯網時代
- 互聯網安全的40個智慧洞見:2015年中國互聯網安全大會文集
- PLC、現場總線及工業網絡實用技術速成
- React:Cross-Platform Application Development with React Native
- OMNeT++與網絡仿真
- TD-LTE無線網絡規劃與設計
- 6G:面向2030年的移動通信
- 網管工具使用與技巧大全
- 夢工廠之材質N次方:Maya材質手冊
- Learning Storm
- Getting Started with Memcached
- 移動互聯網新思維
- 5G智慧交通
- 智能物聯安防視頻技術基礎與應用