构建基础web服务器对golang新手并不难。1. 启动服务器只需调用http.listenandserve(),注册路由使用http.handlefunc并指定处理函数;2. 创建rest api需根据r.method处理get/post请求,返回json可用json.newencoder;3. 中间件可通过封装处理函数实现,如日志记录或cors支持;4. 路由管理可使用http.newservemux提升可控性并便于扩展。掌握这些核心点即可搭建结构清晰的api服务。

构建一个基础的Web服务器对Golang新手来说其实并不难,尤其使用标准库中的
net/http

在Go中启动一个Web服务器非常简单,只需要调用
http.ListenAndServe()
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8080", nil)
}这段代码会启动一个监听8080端口的服务器,并在访问根路径
/

http.HandleFunc
helloHandler
ListenAndServe
host:port
接下来我们可以创建几个类似
/users
/posts
立即学习“go语言免费学习笔记(深入)”;
func usersHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
fmt.Fprintln(w, "[{ID: 1, Name: Alice}]")
case "POST":
fmt.Fprintln(w, "User created")
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/users", usersHandler)
http.ListenAndServe(":8080", nil)
}这样我们就有了一个支持GET和POST方法的
/users

r.Method
json.NewEncoder(w).Encode(data)
虽然
net/http
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received request: %s %s\n", r.Method, r.URL.Path)
next(w, r)
}
}然后在注册路由时包装一下:
http.HandleFunc("/users", loggingMiddleware(usersHandler))如果你需要支持CORS,可以在中间件中设置响应头:
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")这种方式可以灵活地添加认证、限流等功能。
对于稍微复杂一点的项目,直接使用
http.HandleFunc
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/users", loggingMiddleware(usersHandler))
mux.HandleFunc("/posts", postsHandler)
http.ListenAndServe(":8080", mux)
}这里我们创建了一个新的多路复用器
mux
基本上就这些。用
net/http
以上就是Golang新手如何构建Web服务器 使用net/http包创建基础API的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号