Skip to content

项目 2:简易 Web 服务器(Go 特色)

20 行代码搭建 HTTP 服务

基本 HTTP 服务

go
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!\n")
}

func main() {
    http.HandleFunc("/", handler)
    fmt.Println("Server starting on port 8080...")
    http.ListenAndServe(":8080", nil)
}

运行效果

bash
$ go run main.go
Server starting on port 8080...

在浏览器中访问 http://localhost:8080,会看到 Hello, World! 输出。

路由、请求处理

多路由处理

go
package main

import (
    "fmt"
    "net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Welcome to the home page!\n")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About us: We are a Go web server!\n")
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    // 提取 URL 路径参数
    userID := r.URL.Path[len("/user/"):]
    fmt.Fprintf(w, "User ID: %s\n", userID)
}

func main() {
    http.HandleFunc("/", homeHandler)
    http.HandleFunc("/about", aboutHandler)
    http.HandleFunc("/user/", userHandler)
    
    fmt.Println("Server starting on port 8080...")
    http.ListenAndServe(":8080", nil)
}

处理不同 HTTP 方法

go
func apiHandler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "GET":
        fmt.Fprintf(w, "GET request received\n")
    case "POST":
        fmt.Fprintf(w, "POST request received\n")
    case "PUT":
        fmt.Fprintf(w, "PUT request received\n")
    case "DELETE":
        fmt.Fprintf(w, "DELETE request received\n")
    default:
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    }
}

func main() {
    http.HandleFunc("/api", apiHandler)
    // ...
}

接口返回 JSON

返回 JSON 数据

go
package main

import (
    "encoding/json"
    "net/http"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func userJSONHandler(w http.ResponseWriter, r *http.Request) {
    user := User{
        ID:   1,
        Name: "Alice",
        Age:  25,
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user/json", userJSONHandler)
    http.ListenAndServe(":8080", nil)
}

完整示例:RESTful API

go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`
}

var users = []User{
    {ID: 1, Name: "Alice", Age: 25},
    {ID: 2, Name: "Bob", Age: 30},
    {ID: 3, Name: "Charlie", Age: 35},
}

func getUsersHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(users)
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
    userID := r.URL.Path[len("/api/users/"):]
    id, err := strconv.Atoi(userID)
    if err != nil {
        http.Error(w, "Invalid user ID", http.StatusBadRequest)
        return
    }
    
    for _, user := range users {
        if user.ID == id {
            w.Header().Set("Content-Type", "application/json")
            json.NewEncoder(w).Encode(user)
            return
        }
    }
    
    http.Error(w, "User not found", http.StatusNotFound)
}

func main() {
    http.HandleFunc("/api/users", getUsersHandler)
    http.HandleFunc("/api/users/", getUserHandler)
    
    fmt.Println("RESTful API server starting on port 8080...")
    http.ListenAndServe(":8080", nil)
}

运行效果

  1. 访问 http://localhost:8080/api/users

    json
    [
      {"id": 1, "name": "Alice", "age": 25},
      {"id": 2, "name": "Bob", "age": 30},
      {"id": 3, "name": "Charlie", "age": 35}
    ]
  2. 访问 http://localhost:8080/api/users/1

    json
    {"id": 1, "name": "Alice", "age": 25}

© 2026 编程马·菜鸟教程 版权所有