Go语言的HTTP服务器开发
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) }高级路由使用ServeMuxpackage 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应用。