Golang 实现丐版 mock server

代码

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: 
")
	for k, v := range r.Header {
		fmt.Println("	", k, v)
	}
	buf := new(bytes.Buffer)
	buf.ReadFrom(r.Body)
	if buf.String() != "" {
		fmt.Println("body: ", buf.String())
	} else {
		fmt.Println("body:  {}")
	}
}
作者:GI-JOE
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/BenLam/p/15386884.html