目标:用golang实现一个简单的HTTP Server,可以将POST的payload中的内容打印出来
golang环境准备
- 可以参考https://blog.csdn.net/ljyfree/article/details/123810868
- 建议安装的版本最好是不低于golang-1.16
Server的实现
- 直接贴
admin@hpc-1:~/go$ cat http_rpc_server.go
package mainimport ("encoding/json""fmt""log""net/http"
)// 定义一个用于接收请求的结构体
type MapPrinter struct{}// 定义一个用于接收请求的方法
func (m *MapPrinter) PrintMap(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}var payload map[string]interface{}err := json.NewDecoder(r.Body).Decode(&payload)if err != nil {http.Error(w, "Invalid payload", http.StatusBadRequest)return}fmt.Println("Received payload:")for key, value := range payload {fmt.Printf("%s: %v\n", key, value)}w.WriteHeader(http.StatusOK)w.Write([]byte("Map printed successfully\n"))
}func main() {//注册abc-api路由http.HandleFunc("/abc-api", new(MapPrinter).PrintMap)fmt.Println("Server is listening on port 8080...")log.Fatal(http.ListenAndServe(":8080", nil))
}
admin@hpc-1:~/go$
- 终端1上,运行server监听8080端口
admin@hpc-1:~/go$ go run http_rpc_server.go
Server is listening on port 8080...
验证
- 使用curl在终端2上发送POST Request,payload带着map(字典)
admin@hpc-1:~$ curl -vX POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8080/abc-api
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 127.0.0.1:8080...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /abc-api HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.68.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 34
>
* upload completely sent off: 34 out of 34 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Sat, 27 Jan 2024 01:57:59 GMT
< Content-Length: 25
< Content-Type: text/plain; charset=utf-8
<
Map printed successfully
* Connection #0 to host localhost left intact
admin@hpc-1:~$
- 回看终端1,已经将map解析并打印出来
admin@hpc-1:~/go$ go run http_rpc_server.go
Server is listening on port 8080...
Received payload:
key1: value1
key2: value2