在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"。