1 server.go

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func main() {
  7. //http://127.0.0.1:8000/go
  8. http.HandleFunc("/go", myHandler)
  9. _ = http.ListenAndServe("127.0.0.1:8000", nil)
  10. }
  11. // handler函数
  12. func myHandler(w http.ResponseWriter, r *http.Request) {
  13. fmt.Println(r.RemoteAddr, "连接成功")
  14. // 请求方式:GET POST DELETE PUT UPDATE
  15. fmt.Println("method:", r.Method)
  16. // /go
  17. fmt.Println("url:", r.URL.Path)
  18. fmt.Println("header:", r.Header)
  19. fmt.Println("body:", r.Body)
  20. // 回复
  21. w.Write([]byte("hahaha"))
  22. }

2 client.go

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. )
  7. func main() {
  8. resp, _ := http.Get("http://127.0.0.1:8000/go")
  9. defer resp.Body.Close()
  10. // 200 OK
  11. fmt.Println(resp.Status)
  12. fmt.Println(resp.Header)
  13. buf := make([]byte, 1024)
  14. for {
  15. // 接收服务端信息
  16. n, err := resp.Body.Read(buf)
  17. if err != nil && err != io.EOF {
  18. fmt.Println(err)
  19. return
  20. } else {
  21. fmt.Println("读取完毕")
  22. res := string(buf[:n])
  23. fmt.Println(res)
  24. break
  25. }
  26. }
  27. }