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

相关推荐
海绵宝宝贾克斯儿5 分钟前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01126 分钟前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
isyangli_blog30 分钟前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言
三块钱079438 分钟前
【原创】基于视觉大模型gemma-3-4b实现短视频自动识别内容并生成解说文案
开发语言·python·音视频
易只轻松熊38 分钟前
C++(20): 文件输入输出库 —— <fstream>
开发语言·c++·算法
芯眼41 分钟前
ALIENTEK精英STM32F103开发板 实验0测试程序详解
开发语言·c++·stm32·单片机·嵌入式硬件·社交电子
青出于兰1 小时前
C语言| 指针变量的定义
c语言·开发语言
玉笥寻珍2 小时前
筑牢信息安全防线:涉密计算机与互联网隔离的理论实践与风险防控
开发语言·计算机网络·安全·计算机外设·php·安全架构·安全性测试
蓝莓味柯基2 小时前
Lodash isEqual 方法源码实现分析
开发语言
秋野酱2 小时前
python项目参考文献
开发语言·python