在Golang中,我們可以使用標準庫"log"或者第三方庫(如"logrus"、"zap"等)來記錄API請求。下面是一個使用標準庫"log"記錄API請求的簡單示例:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handleRequest)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
logRequest(r)
fmt.Fprintf(w, "Hello, World!")
}
handleRequest函數中,我們調用logRequest函數來記錄請求信息:func logRequest(r *http.Request) {
log.Printf("Request: %s %s %s", r.RemoteAddr, r.Method, r.URL)
log.Printf("Headers: %v", r.Header)
log.Printf("Body: %s", r.Body)
}
這個示例將會記錄每個請求的IP地址、HTTP方法、URL、請求頭和請求體。但是,這個示例有一個問題:r.Body只能被讀取一次。為了解決這個問題,我們可以創建一個自定義的io.ReadCloser,以便多次讀取r.Body:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handleRequest)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
logRequest(r)
fmt.Fprintf(w, "Hello, World!")
}
func logRequest(r *http.Request) {
log.Printf("Request: %s %s %s", r.RemoteAddr, r.Method, r.URL)
log.Printf("Headers: %v", r.Header)
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
return
}
defer r.Body.Close()
log.Printf("Body: %s", bodyBytes)
// Reset the request body so it can be read again by the handler
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
}
現在,你可以在Golang中使用標準庫"log"記錄API請求。如果你需要更高級的功能,可以考慮使用第三方日志庫,如"logrus"或"zap"。