Golang入门指南:构建Web服务器的完整教程
Golang入门指南:构建Web服务器的完整教程 如果您能认可我关于Go语言Web服务器入门的第一篇Medium文章,我将不胜感激。
使用Go(Golang)为初学者构建一个简单的Web服务器
为初学者提供的、使用net/http包的完整且简单的Go(Golang) Web服务器。
阅读时间:4分钟
更多关于Golang入门指南:构建Web服务器的完整教程的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang入门指南:构建Web服务器的完整教程的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
package main
import (
"fmt"
"net/http"
)
func main() {
// 注册路由处理函数
http.HandleFunc("/", homeHandler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/api/data", apiHandler)
// 启动服务器监听8080端口
fmt.Println("服务器启动在 http://localhost:8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("服务器启动失败:", err)
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
// 设置响应头
w.Header().Set("Content-Type", "text/html")
// 写入响应内容
fmt.Fprintf(w, `
<!DOCTYPE html>
<html>
<head><title>Go Web服务器</title></head>
<body>
<h1>欢迎来到Go Web服务器</h1>
<p>这是一个使用net/http包构建的简单示例</p>
<a href="/about">关于我们</a>
</body>
</html>
`)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `
<!DOCTYPE html>
<html>
<head><title>关于我们</title></head>
<body>
<h1>关于这个Web服务器</h1>
<p>使用Go语言的标准库net/http构建</p>
<a href="/">返回首页</a>
</body>
</html>
`)
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
// 设置JSON响应头
w.Header().Set("Content-Type", "application/json")
// 返回JSON数据
jsonResponse := `{"status": "success", "message": "API响应正常", "data": [1, 2, 3]}`
fmt.Fprint(w, jsonResponse)
}
// 进阶示例:使用自定义多路复用器和中间件
package main
import (
"log"
"net/http"
"time"
)
// 日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
})
}
// 认证中间件
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token != "Bearer secret-token" {
http.Error(w, "未授权", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
// 创建自定义多路复用器
mux := http.NewServeMux()
// 静态文件服务
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
// 注册路由
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("首页"))
})
mux.HandleFunc("/api/protected", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("受保护的API端点"))
})
// 应用中间件
handler := loggingMiddleware(mux)
protectedHandler := authMiddleware(handler)
// 启动服务器
log.Println("服务器启动在 :8080")
http.ListenAndServe(":8080", protectedHandler)
}
// 处理不同HTTP方法的示例
package main
import (
"encoding/json"
"net/http"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
var users = []User{
{ID: 1, Name: "张三", Email: "zhangsan@example.com"},
{ID: 2, Name: "李四", Email: "lisi@example.com"},
}
func main() {
http.HandleFunc("/users", usersHandler)
http.HandleFunc("/users/", userDetailHandler)
http.ListenAndServe(":8080", nil)
}
func usersHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case "GET":
json.NewEncoder(w).Encode(users)
case "POST":
var newUser User
if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
users = append(users, newUser)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newUser)
default:
http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
}
}
func userDetailHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// 这里应该解析URL参数获取用户ID
// 简化示例,直接返回第一个用户
if r.Method == "GET" {
json.NewEncoder(w).Encode(users[0])
} else {
http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
}
}
这些示例展示了使用Go标准库net/http构建Web服务器的核心功能,包括基本路由、中间件实现、不同HTTP方法处理以及JSON响应。


