Go语言的HTTP服务器开发
2026/4/16 18:15:15 网站建设 项目流程

Go语言的HTTP服务器开发

HTTP服务器基础

Go语言提供了标准的net/http包,用于构建HTTP服务器和客户端。使用这个包可以快速创建高性能的Web应用。

基本使用

创建简单的HTTP服务器

package main import ( "fmt" "net/http" ) func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", helloHandler) fmt.Println("Server starting on port 8080...") http.ListenAndServe(":8080", nil) }

处理不同的路由

package main import ( "fmt" "net/http" ) func homeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Home Page") } func aboutHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "About Page") } func main() { http.HandleFunc("/", homeHandler) http.HandleFunc("/about", aboutHandler) fmt.Println("Server starting on port 8080...") http.ListenAndServe(":8080", nil) }

高级路由

使用ServeMux

package main import ( "fmt" "net/http" ) func homeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Home Page") } func aboutHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "About Page") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", homeHandler) mux.HandleFunc("/about", aboutHandler) fmt.Println("Server starting on port 8080...") http.ListenAndServe(":8080", mux) }

使用第三方路由库

gorilla/mux为例:

package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func homeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Home Page") } func userHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) userID := vars["id"] fmt.Fprintf(w, "User ID: %s", userID) } func main() { r := mux.NewRouter() r.HandleFunc("/", homeHandler) r.HandleFunc("/users/{id}", userHandler) fmt.Println("Server starting on port 8080...") http.ListenAndServe(":8080", r) }

处理请求和响应

获取请求参数

package main import ( "fmt" "net/http" ) func searchHandler(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() keyword := query.Get("q") fmt.Fprintf(w, "Search keyword: %s", keyword) } func main() { http.HandleFunc("/search", searchHandler) http.ListenAndServe(":8080", nil) }

处理POST请求

package main import ( "fmt" "net/http" "io/ioutil" ) func submitHandler(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintf(w, "Error reading body: %v", err) return } defer r.Body.Close() fmt.Fprintf(w, "Received: %s", body) } else { w.WriteHeader(http.StatusMethodNotAllowed) fmt.Fprintf(w, "Method not allowed") } } func main() { http.HandleFunc("/submit", submitHandler) http.ListenAndServe(":8080", nil) }

中间件

创建自定义中间件

package main import ( "fmt" "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) duration := time.Since(start) fmt.Printf("%s %s %v\n", r.Method, r.URL.Path, duration) }) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") } func main() { http.HandleFunc("/", helloHandler) wrappedHandler := loggingMiddleware(http.DefaultServeMux) http.ListenAndServe(":8080", wrappedHandler) }

静态文件服务

package main import ( "net/http" ) func main() { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") }) http.ListenAndServe(":8080", nil) }

示例:完整的HTTP服务器

package main import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/gorilla/mux" ) type User struct { ID int `json:"id"` Name string `json:"name"` Age int `json:"age"` } var users = []User{ {ID: 1, Name: "John", Age: 30}, {ID: 2, Name: "Jane", Age: 25}, } func getUsers(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(users) } func getUser(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id, err := strconv.Atoi(vars["id"]) if err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Invalid user ID") return } for _, user := range users { if user.ID == id { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) return } } w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "User not found") } func createUser(w http.ResponseWriter, r *http.Request) { var user User err := json.NewDecoder(r.Body).Decode(&user) if err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Invalid request body") return } defer r.Body.Close() user.ID = len(users) + 1 users = append(users, user) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(user) } func main() { r := mux.NewRouter() r.HandleFunc("/users", getUsers).Methods("GET") r.HandleFunc("/users/{id}", getUser).Methods("GET") r.HandleFunc("/users", createUser).Methods("POST") r.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) fmt.Println("Server starting on port 8080...") http.ListenAndServe(":8080", r) }

性能优化

  • 使用http.Server结构体来自定义服务器配置
  • 启用HTTP/2以提高性能
  • 使用连接池管理数据库连接
  • 实现请求超时处理
  • 使用缓存减少重复计算

总结

Go语言的net/http包提供了强大的HTTP服务器功能,支持路由、中间件、静态文件服务等特性。通过合理使用这些功能,可以构建高性能、可维护的Web应用。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询