document.writeln('');

在公车被猛烈进入爽文,啊灬轻点大JI巴太粗又长A片,亚洲色欲AV成人无码久久精品 ,国产大片内射1区2区,久久久网址,亚洲一区二区三区免费视频,精品欧美一区二区三区久久久,久久国产精品-久久精品

當前位置:首頁 > 云服務器 > Golang使用nethttp構建簡單API服務

Golang使用nethttp構建簡單API服務

游戲科技網2026年09月14日 21:43云服務器80
最常見原因是監聽地址寫成了"localhost:8080"或"127.0.0.1:8080",應改用":8080"監聽所有接口;此外需檢查端口占用、Docker映射、路由前綴匹配邏輯、JSON解析時機及生產環境應使用http.Server而非ListenAndServe。

為什么 http.ListenAndServe 啟動后沒報錯卻訪問不了?

最常見原因是監聽地址寫成了 "localhost:8080" 或 "127.0.0.1:8080",導致外部網絡(包括 Docker 容器外、云服務器安全組外)無法連接。Go 的 net/http 默認只綁定到本地回環地址。

  • 對外提供服務時,必須用 ":8080"(空主機名),表示監聽所有可用網絡接口
  • 若端口被占用,http.ListenAndServe 會返回 "address already in use" 錯誤;但若監聽成功卻無響應,優先檢查綁定地址
  • 在 Docker 中運行時,還要確認 EXPOSE 和宿主機 -p 映射是否匹配

如何用 http.ServeMux 實現路徑路由?

http.ServeMux 是 Go 標準庫默認的 HTTP 路由器,支持前綴匹配而非完全匹配,這點容易引發意料外的行為。

  • "/api" 會匹配 /api、/api/users、甚至 /apixxx —— 因為它只是字符串前綴判斷
  • 要精確匹配,需手動檢查 r.URL.Path,或改用第三方路由器(如 gorilla/mux、chi)
  • 注冊順序有影響:后注冊的 handler 若前綴覆蓋了前面的,可能“吃掉”本該由更具體規則處理的請求

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

func main() {

    mux := http.NewServeMux()

    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {

        w.WriteHeader(http.StatusOK)

        w.Write([]byte("ok"))

    })

    // 注意:這個會匹配 /api 和 /api/xxx,但不會匹配 /apiuser

    mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {

        if r.URL.Path == "/api/" {

            http.Error(w, "use subpath", http.StatusBadRequest)

            return

        }

        w.Write([]byte("data"))

    })

    http.ListenAndServe(":8080", mux)

}

怎么讀取 JSON 請求體并避免 i/o timeout 或 invalid character?

直接調用 json.Decode(r.Body) 前,必須確保 r.Body 沒被其他邏輯提前讀取(比如日志中間件調用了 r.Body.Read 或 io.ReadAll),否則后續解碼會得到空內容或 EOF。

baidu-map-jsapi-three

使用 MapV-Three 構建專業的 3D 地圖和 GIS 應用 - 基于 Z-up 坐標系的 3D 地圖庫,支持地圖編輯、測量工具、要素繪制、數據管理等地理可視化功能。適用于創建地圖編輯器、測量工具、空間數據可視化等 Web-GIS 應用。

下載
  • 務必在 handler 開頭就處理請求體,不要依賴中間件自動解析
  • 設置 r.Header.Get("Content-Type") 檢查是否為 "application/json",避免非 JSON 請求觸發解析錯誤
  • 使用 json.NewDecoder 而非 json.Unmarshal 可減少內存拷貝,但兩者都要求 body 可讀一次
  • 超時通常來自客戶端未發送完整 body,或服務端未設 http.Server.ReadTimeout

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

type User struct {

    Name string `json:"name"`

    Age  int    `json:"age"`

}

 

func createUser(w http.ResponseWriter, r *http.Request) {

    if r.Method != "POST" {

        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)

        return

    }

    if r.Header.Get("Content-Type") != "application/json" {

        http.Error(w, "content-type must be application/json", http.StatusBadRequest)

        return

    }

 

    var u User

    decoder := json.NewDecoder(r.Body)

    if err := decoder.Decode(&u); err != nil {

        http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest)

        return

    }

 

    w.Header().Set("Content-Type", "application/json")

    json.NewEncoder(w).Encode(map[string]string{"status": "created"})

}

為什么生產環境不建議直接用 http.ListenAndServe?

標準 http.ListenAndServe 啟動的 server 缺少對優雅關閉、超時控制、連接限制等關鍵生產特性的配置能力。一旦進程收到 SIGINT/SIGTERM,它會立即退出,正在處理的請求可能被中斷。

立即學習“go語言免費學習筆記(深入)”;

  • 必須用 http.Server 結構體顯式構造,并設置 ReadTimeout、WriteTimeout、IdleTimeout
  • 關閉時需調用 srv.Shutdown(),配合 context.WithTimeout 等待活躍連接完成
  • 日志、panic 恢復、CORS、gzip 壓縮等都需要自己封裝中間件,標準庫只提供最基礎骨架

真正上線時,http.ListenAndServe 只適合原型驗證——它掩蓋了連接生命周期管理的復雜性。

“Golang使用nethttp構建簡單API服務” 的相關文章