GO语言实现一个简单的HTTP服务器和客户端

GO语言实现一个简单的HTTP服务器和客户端

目录结构:

image.png

服务端代码:


package main

import (
   "encoding/json"
   "net/http"
   "strconv"
)

func main() {
   http.HandleFunc("/add", func(w http.ResponseWriter, r *http.Request) {
      _ = r.ParseForm()
      a, _ := strconv.Atoi(r.Form["a"][0])
      b, _ := strconv.Atoi(r.Form["b"][0])

      res, _ := json.Marshal(map[string]int{
         "data": a + b,
      })
      w.Header().Set("Content-Type","application/json")
      _, _ = w.Write(res)
   })

   _ = http.ListenAndServe(":8000", nil)
}



客户端代码:

package main

import (
   "encoding/json"
   "fmt"
   "github.com/kirinlabs/HttpRequest"
)

type rpcResponse struct {
   Data int `json:"data"`
}

func add(a, b int) int {
   req := HttpRequest.NewRequest()
   res, _ := req.Get(fmt.Sprintf("http://localhost:8000/%s?a=%d&b=%d", "add", a, b))
   body, _ := res.Body()

   var rpc rpcResponse
   _ = json.Unmarshal(body, &rpc)

   return rpc.Data
}
func main() {
   res := add(1, 2)
   fmt.Println(res)
}



最后编辑于:2022/01/08作者: 牛逼PHP

发表评论