《Web Development with Go》写一个简单的LoggingMiddleware

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《Web Development with Go》写一个简单的LoggingMiddleware相关的知识,希望对你有一定的参考价值。

main.go

package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

func loggingHandler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		log.Printf("Started %s %s", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
		log.Printf("Completed %s in %v", r.URL.Path, time.Since(start))
	})
}

func index(w http.ResponseWriter, r *http.Request) {
	log.Println("Executing index handler")
	fmt.Fprintf(w, "welcome!")
}

func about(w http.ResponseWriter, r *http.Request) {
	log.Println("Executing about handler")
	fmt.Fprintf(w, "Go Middleware!")
}

func iconHandler(w http.ResponseWriter, r *http.Request) {

}

func main() {
	http.HandleFunc("/favicon.ico", iconHandler)
	indexHandler := http.HandlerFunc(index)
	aboutHandler := http.HandlerFunc(about)
	http.Handle("/", loggingHandler(indexHandler))
	http.Handle("/about", loggingHandler(aboutHandler))

	server := &http.Server{
		Addr: ":8080",
	}
	log.Println("Listening...")
	server.ListenAndServe()

}

  技术图片

以上是关于《Web Development with Go》写一个简单的LoggingMiddleware的主要内容,如果未能解决你的问题,请参考以下文章

《Web Development with Go》JWT认证满意版

在 Rails 中隐藏按钮(Agile Web Development with Rails 书)

Building RESTful Web services with Go.pdf

<Test-Driven Development with Python;学习笔记 第一部分 测试驱动开发基础

<Test-Driven Development with Python;学习笔记 第一部分 测试驱动开发基础

build-web-application-with-golang学习笔记