go的net/http库通过handler和handlefunc等核心概念,可快速构建http服务器和客户端。1. 创建http服务器需使用http.handlefunc注册处理函数,并调用http.listenandserve启动服务;2. 发送get请求可通过http.get实现;3. 处理post请求需解析r.form并读取表单数据;4. 自定义客户端超时时间可通过设置http.client的timeout字段;5. 操作header信息通过r.header.get读取并用w.header().set设置;6. 实现中间件可通过包装handler的方式;7. 管理cookie则借助http.cookie结构体进行读写操作。这些功能使开发者能够高效完成常见web任务。

Go的
net/http

Go的
net/http

创建一个HTTP服务器,最简单的方法是使用
http.HandleFunc
http.ListenAndServe
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}这段代码注册了一个处理根路径的handler函数,当有请求到达根路径时,会返回"Hello, World!"。
http.ListenAndServe

使用
http.Get
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
resp, err := http.Get("https://www.example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}这段代码发送一个GET请求到
https://www.example.com
resp.Body
处理POST请求需要从
Request
package main
import (
"fmt"
"net/http"
)
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
fmt.Fprintf(w, "POST request successful\n")
name := r.FormValue("name")
address := r.FormValue("address")
fmt.Fprintf(w, "Name = %s\n", name)
fmt.Fprintf(w, "Address = %s\n", address)
} else {
fmt.Fprintf(w, "Only POST method is supported.")
}
}
func main() {
http.HandleFunc("/form", formHandler)
http.ListenAndServe(":8080", nil)
}这个例子中,
r.ParseForm()
r.FormValue
默认情况下,
http.Client
http.Client
Timeout
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
client := &http.Client{
Timeout: time.Second * 10,
}
resp, err := client.Get("https://www.example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// ... 处理响应
}这段代码创建了一个超时时间为10秒的HTTP客户端。
可以通过
Request
Header
Header
map[string][]string
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
userAgent := r.Header.Get("User-Agent")
fmt.Fprintf(w, "User-Agent: %s\n", userAgent)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}这个例子中,读取了请求的
User-Agent
Content-Type
HTTP中间件是一种在处理请求之前或之后执行某些操作的模式。可以通过创建一个函数来包装现有的handler来实现中间件。
package main
import (
"fmt"
"net/http"
"log"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.Handle("/", loggingMiddleware(http.HandlerFunc(handler)))
http.ListenAndServe(":8080", nil)
}这个例子中,
loggingMiddleware
可以使用
http.Cookie
http.ReadRequest
http.SetCookie
package main
import (
"fmt"
"net/http"
)
func cookieHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("mycookie")
if err != nil {
fmt.Println("Cookie not found")
cookie = &http.Cookie{
Name: "mycookie",
Value: "initial value",
Path: "/",
}
}
fmt.Fprintf(w, "Cookie value: %s\n", cookie.Value)
cookie.Value = "updated value"
http.SetCookie(w, cookie)
}
func main() {
http.HandleFunc("/cookie", cookieHandler)
http.ListenAndServe(":8080", nil)
}这个例子中,读取名为"mycookie"的cookie,如果不存在则创建一个,然后更新cookie的值并设置到响应中。
这些示例涵盖了
net/http
以上就是Golang中net/http库如何使用 详解HTTP服务器与客户端实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号