文档
- https://pkg.go.dev/net
- https://pkg.go.dev/net/http
- https://pkg.go.dev/net/http/httputil
- https://pkg.go.dev/net/rpc
- https://pkg.go.dev/net/rpc/jsonrpc
- https://pkg.go.dev/net/url
- https://pkg.go.dev/net/mail
SSH 和 SFTP 及其相关库了解
说明
- TCP 网络编程: TCP 底层处理逻辑(理解)
- HTTP 网络编程: 基于 TCP 的封装实现的 HTTP 协议(重点)
- RPC/JSON-RPC 网络编程: 远程协议调用, 是写微服务用的协议(重点)
快速构建一个 HTTP 服务器
go
package main
import (
"fmt"
"net/http"
)
// 1.设计 API
// GET / # 检查服务器状态
// GET /articles # 文章列表接口
// 2.定义处理函数
func CheckHealth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"errno": 0, msg: "server is running", "data": null}`)
}
func ListArticles(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"errno": 0, msg: "success", "data": []}`)
}
func LoggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("请求开始", r.URL.Path)
next.ServeHTTP(w, r)
fmt.Println("请求结束")
})
}
func main() {
// 3.创建 http 服务实例 & 注册路由
server := http.NewServeMux()
server.HandleFunc("/", CheckHealth)
server.HandleFunc("/articles", ListArticles)
// 4.定义中间件
handler := LoggerMiddleware(server)
// 5.启动 http 服务, 监听客户端请求
http.ListenAndServe("127.0.0.1:8080", handler)
}快速构建一个 HTTP 客户端
go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func main() {
sendGetRequst()
sendPostRequst()
}
// 使用默认的http客户端发送get请求
func sendGetRequst() {
response, err := http.Get("http://127.0.0.1:3000/query?keyword=golang")
if err != nil {
fmt.Println("Network error", err)
return
}
body, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println("ReadAll error", err)
return
}
fmt.Println(string(body))
}
// 使用默认的http客户端发送post请求
func sendPostRequst() {
byteData, _ := json.Marshal(map[string]string{
"email": "test@example.com",
"password": "123456",
})
response, err := http.Post("http://127.0.0.1:3000/json", "application/json", bytes.NewBuffer(byteData))
if err != nil {
fmt.Println("Network error", err)
}
body, err := io.ReadAll(response.Body)
if err != nil {
fmt.Println("ReadAll error", err)
return
}
fmt.Println(string(body))
}