跳到主要内容

net库

  • net = network,是 Go 标准库中负责网络编程的一组包
包主要作用常见场景
netTCP、UDP、IP、网络连接Socket 服务、TCP 服务
net/httpHTTP Server / ClientWeb API、调用第三方 API
net/urlURL 解析、构造Query 参数、URL 处理
net/mail邮件格式解析解析邮件
net/rpcRPC 通信RPC 服务
net/smtpSMTP 协议发送邮件
net/textproto文本协议HTTP、SMTP 等底层支持

net/http​

  • 启动 HTTP 服务
  • 注册路由
  • 接收 Request
  • 返回 Response
go
package main

import (
"fmt"
"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello Go")
}

func main() {
http.HandleFunc("/hello", hello)

http.ListenAndServe(":8080", nil)
}

注册路由​

  • http.HandleFunc
go
http.HandleFunc("/hello", hello)

启动服务​

  • http.ListenAndServe
go
// nil表示没有传自定义 Handler
http.ListenAndServe(":8080", nil)