源码来自 https://github.com/deis/mock-http-server
主要作用是开启一个本地的监听8080端口的http服务器,能够打印客户端的请求,方便进行调试。
package main
import (
"fmt"
"log"
"net/http"
)
// Log the HTTP request
func logHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
}
// mockHandler responds with "ok" as the response body
func mockHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "ok\n")
}
// rootHandler used to process all inbound HTTP requests
func rootHandler(w http.ResponseWriter, r *http.Request) {
logHandler(w, r)
mockHandler(w, r)
}
// Start an HTTP server which dispatches to the rootHandler
func main() {
http.HandleFunc("/", rootHandler)
port := "8080"
log.Printf("server is listening on %v\n", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
panic(err)
}
}
如果需要打印header,请参考:https://www.cnblogs.com/5bug/p/8494953.html
func helloFunc(w http.ResponseWriter, r *http.Request) {
fmt.Println("打印Header参数列表:")
if len(r.Header) > 0 {
for k,v := range r.Header {
fmt.Printf("%s=%s\n", k, v[0])
}
}
fmt.Println("打印Form参数列表:")
r.ParseForm()
if len(r.Form) > 0 {
for k,v := range r.Form {
fmt.Printf("%s=%s\n", k, v[0])
}
}