使用go的net/http包可快速搭建Web服务器,无需复杂框架。2. 通过http.HandleFunc注册路由,http.ListenAndServe启动服务。3. 支持多路由和GET/POST请求处理,区分方法并解析表单。4. 利用http.FileServer提供静态文件服务。5. 基础功能完备,适合扩展。
想用Golang快速搭建一个简单的Web服务器?其实并不难。Go语言自带的net/http包已经足够强大,无需引入复杂框架,就能实现路由、处理请求和返回响应。下面带你一步步从零开始写一个基础但完整的Web服务。
1. 创建最简单的HTTP服务器
先写一段最基础的代码,让服务器跑起来:
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端口。
2. 添加多个路由处理
实际项目中通常需要多个接口。可以通过不同的路径注册不同处理器:
立即学习“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来管理路由,它基于前缀匹配,所以路径顺序和精确性很重要。
3. 处理GET和POST请求
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()才能读取表单内容。
4. 静态文件服务
前端页面或资源文件(如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是打好基础的关键。
css js 前端 go golang 处理器 go语言 浏览器 端口 ai 路由 golang gin css echo Static 接口 Go语言 JS http