使用Go的net/http包可快速搭建Web服务器,无需复杂框架。2. 通过http.HandleFunc注册路由,http.ListenAndServe启动服务。3. 支持多路由和GET/POST请求处理,区分方法并解析表单。4. 利用http.FileServer提供静态文件服务。5. 基础功能完备,适合扩展。

想用Golang快速搭建一个简单的Web服务器?其实并不难。Go语言自带的net/http包已经足够强大,无需引入复杂框架,就能实现路由、处理请求和返回响应。下面带你一步步从零开始写一个基础但完整的Web服务。
先写一段最基础的代码,让服务器跑起来:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go Web Server!")
}
func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("Server is running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
保存为main.go,运行go run main.go,然后在浏览器打开http://localhost:8080就能看到输出。这个例子中,HandleFunc注册了根路径的处理函数,ListenAndServe启动服务监听8080端口。
实际项目中通常需要多个接口。可以通过不同的路径注册不同处理器:
立即学习“go语言免费学习笔记(深入)”;
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is the about page.")
}
func main() {
http.HandleFunc("/", helloHandler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/user", userHandler)
fmt.Println("Server is running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
现在访问/about会显示对应内容。注意:Go默认使用DefaultServeMux来管理路由,它基于前缀匹配,所以路径顺序和精确性很重要。
本书全面介绍PHP脚本语言和MySOL数据库这两种目前最流行的开源软件,主要包括PHP和MySQL基本概念、PHP扩展与应用库、日期和时间功能、PHP数据对象扩展、PHP的mysqli扩展、MySQL 5的存储例程、解发器和视图等。本书帮助读者学习PHP编程语言和MySQL数据库服务器的最佳实践,了解如何创建数据库驱动的动态Web应用程序。
385
Web服务常需区分请求方法。比如用户提交表单通常是POST:
func userHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprintf(w, `
<form method="POST">
<input type="text" name="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
`)
} else if r.Method == "POST" {
r.ParseForm()
name := r.Form.Get("name")
fmt.Fprintf(w, "Hello, %s!", name)
}
}
这段代码在GET时返回一个简单表单,POST时解析表单数据并回应。记得调用ParseForm()才能读取表单内容。
前端页面或资源文件(如CSS、JS、图片)需要静态服务。Go可以用http.FileServer轻松实现:
func main() {
http.HandleFunc("/", helloHandler)
http.HandleFunc("/about", aboutHandler)
// 提供static目录下的静态文件
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
fmt.Println("Server is running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
只要在项目根目录创建static文件夹,放一张图片logo.png,就可以通过http://localhost:8080/static/logo.png访问。
基本上就这些。一个轻量、可运行的Web服务器已经成型。随着需求增长,你可以引入第三方路由库(如Gorilla Mux)或框架(如Echo、Gin),但理解原生net/http是打好基础的关键。
以上就是Golang初学者开发简单Web服务器实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号