坚持为自己每月写1篇笔记

Retreat Hell!
We Just Got Here.

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: \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:  {}")
	}
}
posted @ 2021-10-09 17:35  l||||||l  阅读(158)  评论(0编辑  收藏  举报