go接收post来的json数据

公司对某套服务进行压力测试,有个服务需要一个端点接收post数据 写个server 充当挡板,暂时还没优化的需求

cat postHttpServer.go
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)
func  mockWebhook(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/webhook" {
		http.Error(w, "404 not found.", http.StatusNotFound)
		return
	}
		switch r.Method {
		case "POST":
			defer r.Body.Close()
			con, _ := ioutil.ReadAll(r.Body)

			fmt.Fprintf(w, "接收到数据:"+string(con))
			fmt.Println("收到来自主机" + r.RemoteAddr + "的数据:" + string(con))
		default:
			fmt.Fprintf(w, "Sorry, only POST methods are supported.")
		}

}

func main() {
	http.HandleFunc("/webhook", mockWebhook)
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

test

curl -H "Content-Type:application/json" -X POST -d '{"key_name":"key1","content":"contexssst"}' http://127.0.0.1:8080/webhook -v

你可能感兴趣的:(go,golang,json,开发语言)