Golang 實現丐版 mock server
阿新 • • 發佈:2021-10-09
程式碼
作者:GI-JOE 出處:http://www.cnblogs.com/BenLam/ 本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連線,否則保留追究法律責任的權利。package main import ( "bytes" "encoding/json" "fmt" "net/http" ) type BaseJsonBean struct { Status string `json:"status"` } func main() { fmt.Println("ip: 127.0.0.1:80") response, _ := json.Marshal(&BaseJsonBean{"ok"}) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { printDetails(r) w.Write([]byte(response)) }) http.ListenAndServe(":80", nil) } func printDetails(r *http.Request) { fmt.Println("- - - - - - - - - - - - -") fmt.Println("Host:", r.Host) fmt.Println("url: ", r.Method, r.URL) fmt.Printf("header: \n") for k, v := range r.Header { fmt.Println("\t", k, v) } buf := new(bytes.Buffer) buf.ReadFrom(r.Body) if buf.String() != "" { fmt.Println("body: ", buf.String()) } else { fmt.Println("body: {}") } }