golang实现一个简单的HTTP server

目标:用golang实现一个简单的HTTP Server,支持指定监听端口,将收到的POST的payload中的内容打印出来

golang环境准备

Server的实现

  • 直接贴

    admin@hpc-1:~/go$ cat http_rpc_server.go
    package main

    import (
    "fmt"
    "log"
    "flag"
    "net/http"
    "encoding/json"
    )

    // 定义一个用于接收请求的结构体
    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() {
    //获取监听端口,默认8080
    port := flag.String("p", "8080", "指定监听端口")
    // 解析命令行参数
    flag.Parse()

    复制代码
      //注册abc-api路由
      http.HandleFunc("/abc-api", new(MapPrinter).PrintMap)
    
      fmt.Println("Server is listening on port %s...", *port)
      log.Fatal(http.ListenAndServe(":" + *port, nil))

    }
    admin@hpc-1:~/go$

  • 编译

    admin@hpc-1:~/go go build -o http_rpc_server http_rpc_server.go admin@hpc-1:~/go

  • 终端1上,运行server监听8090端口

    admin@hpc-1:~/go$ ./http_rpc_server -p 8090
    Server is listening on port 8090...

验证

  • 使用curl在终端2上发送POST Request,payload带着map(字典)

    admin@hpc-1:~$ curl -vX POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://localhost:8090/abc-api
    Note: Unnecessary use of -X or --request, POST is already inferred.

    • Trying 127.0.0.1:8090...
    • TCP_NODELAY set
    • Connected to localhost (127.0.0.1) port 8090 (#0)

    POST /abc-api HTTP/1.1
    Host: localhost:8090
    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: Sun, 28 Jan 2024 00:51:25 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$ ./http_rpc_server -p 8090
    Server is listening on port %s... 8090
    Received payload:
    key1: value1
    key2: value2

相关推荐
阿里嘎多学长27 分钟前
2026-09-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
weixin_307779132 小时前
C++代码实现MATLAB中的ode23tb函数功能
开发语言·c++·算法·matlab
2601_966949652 小时前
为什么量化回测中 for 循环比 DataFrame 慢三个数量级?从向量化原理讲起
开发语言·python·pandas·股票数据·quantdash
边境悍匪4 小时前
蜗牛学苑 Java 智能体学习 Day45|Knife4j+SpringBoot3、书城项目整合 MyBatis 思维导图复盘
java·开发语言·vue.js·学习·spring
我的xiaodoujiao4 小时前
Django 基础知识详细图文教程 9-Django 模板引擎 2
开发语言·数据库·后端·django
菜鸟~noob2334 小时前
【太空电子战】从CCS到Meadowlands:反通信系统的二十年演进史【含matlab代码】
开发语言·matlab
quantdash_cc5 小时前
量化策略为什么需要实时行情数据?从信号产生到交易决策的时间差说起
开发语言·python·数据分析·量化交易·股票数据·quantdash
逆向编程7 小时前
QGIS地图投影(CRS坐标参照系)设置
开发语言
free-elcmacom7 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
程序员阿鹏7 小时前
简单介绍一下软引用
java·开发语言·jvm·数据结构·后端