答案:Golang通过net/http库处理HTTP请求,使用http.HandleFunc注册路由,http.ListenAndServe启动服务器,从*http.Request获取参数、头信息等,结合ResponseWriter返回响应,支持静态文件、JSON输出及状态码设置。

在Golang中处理HTTP请求主要通过标准库net/http实现,它提供了简单而强大的接口来创建HTTP服务器和客户端。下面介绍如何使用它来处理常见的HTTP服务端请求。
使用http.HandleFunc可以注册一个URL路径对应的处理函数,然后通过http.ListenAndServe启动服务器。
示例代码:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
fmt.Println("Server starting on :8080...")
http.ListenAndServe(":8080", nil)
}
访问 http://localhost:8080/hello 将返回 "Hello, World!"。
立即学习“go语言免费学习笔记(深入)”;
处理HTTP请求时,常需要获取查询参数、请求头、表单数据等信息。这些都可以从*http.Request对象中提取。
常见操作包括:
示例:
func userInfoHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
name := r.FormValue("name")
age := r.FormValue("age")
fmt.Fprintf(w, "Name: %s, Age: %s", name, age)
}
对于更复杂的路由需求,可以使用http.ServeMux进行路径分发,也可以直接用http.FileServer提供静态资源。
例如提供./static/目录下的文件:
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
通过ResponseWriter可控制输出内容和状态码。
例如返回JSON数据:
func jsonHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
data := `{"message": "success"}`
w.Write([]byte(data))
}
注意先调用Header().Set和WriteHeader,再写入响应体。
基本上就这些。net/http足够应对大多数基础Web服务场景,结构清晰且无需依赖外部库。不复杂但容易忽略细节,比如表单解析前是否调用了r.ParseForm()(通常FormValue会自动处理),或响应头设置时机。
以上就是如何在Golang中使用net/http处理HTTP请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号