使用net/http可快速创建HTTP服务器,通过HandleFunc注册路由并用ListenAndServe启动服务;2. 可根据r.Method处理不同请求方法,并返回相应内容或错误;3. 利用http.FileServer提供静态文件服务,配合StripPrefix处理路径前缀;4. 通过自定义http.Server结构体可设置超时、TLS等参数,提升服务控制力。

用Golang搭建一个简单的HTTP服务器非常直接,标准库net/http提供了所需的所有功能,无需引入第三方框架。下面介绍如何快速实现一个基础的HTTP服务。
只需几行代码就能启动一个监听指定端口的Web服务:
package main
<p>import (
"fmt"
"net/http"
)</p><p>func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, 你好!这是你的第一个Go HTTP服务器")
}</p><p>func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("服务器运行在 <a href="https://www.php.cn/link/cbb686245ece57c9827c4bc0d0654a8e">https://www.php.cn/link/cbb686245ece57c9827c4bc0d0654a8e</a>")
http.ListenAndServe(":8080", nil)
}</p>运行后访问 https://www.php.cn/link/cbb686245ece57c9827c4bc0d0654a8e 即可看到返回内容。这里使用了HandleFunc注册路由,ListenAndServe启动服务。
你可以为不同路径设置不同的处理函数:
立即学习“go语言免费学习笔记(深入)”;
func userHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprintf(w, "获取用户信息")
} else {
http.Error(w, "仅支持GET请求", http.StatusMethodNotAllowed)
}
}
<p>func main() {
http.HandleFunc("/", helloHandler)
http.HandleFunc("/user", userHandler)
http.ListenAndServe(":8080", nil)
}</p>通过判断r.Method可以区分GET、POST等请求类型,配合http.Error返回标准错误响应。
如果需要提供CSS、JS或图片等静态资源,可以用http.FileServer:
func main() {
// 提供当前目录下的静态文件
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
<pre class='brush:php;toolbar:false;'>http.HandleFunc("/", helloHandler)
fmt.Println("服务已启动:https://www.php.cn/link/cbb686245ece57c9827c4bc0d0654a8e")
http.ListenAndServe(":8080", nil)}
访问/static/style.css时,服务器会尝试返回./static/style.css文件。
通过构建http.Server结构体,可以获得更灵活的配置能力:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", helloHandler)
mux.HandleFunc("/user", userHandler)
<pre class='brush:php;toolbar:false;'>server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
fmt.Println("服务运行中...")
server.ListenAndServe()}
这种方式能设置超时、TLS、连接池等参数,适合生产环境使用。
基本上就这些。Golang的HTTP服务器设计简洁,上手快,适合API服务或小型Web应用。随着需求增长,可逐步引入中间件、路由库(如gorilla/mux)或框架(如Gin)来扩展功能。
以上就是Golang如何实现简单的HTTP服务器_Golang HTTP Server基础搭建方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号