Home  >  Article  >  Backend Development  >  How to verify HTTP response status code in Golang?

How to verify HTTP response status code in Golang?

WBOY
WBOYOriginal
2024-06-05 20:28:00901browse

The methods to verify the HTTP response status code in Golang are: use http.Response.StatusCode to directly compare the response status code with the expected value. Create a custom error type that contains a status code and error message, and verify the status code by catching the error.

在 Golang 中如何验证 HTTP 响应状态代码?

How to verify HTTP response status code in Golang

Using net/http package in Golang When sending an HTTP request, it is important to verify the response status code. This helps handle server-side errors, configuration issues, and other network issues.

Using http.Response.StatusCode

http.Response type contains a StatusCode field , indicating the status code of the HTTP response. To verify the status code, you can simply compare StatusCode with the expected value:

package main

import (
  "fmt"
  "net/http"
  "net/http/httptest"
)

func main() {
  // 创建一个模拟响应
  resp := httptest.NewRecorder()

  // 设置状态代码
  resp.WriteHeader(http.StatusOK)

  if resp.Code == http.StatusOK {
    fmt.Println("成功")
  }
}

Use a custom error type

An alternative validation response The method for status codes is to create a custom error type that contains the status code and error message:

package main

import (
  "errors"
  "fmt"
  "net/http"
)

type HTTPError struct {
  Code int
  Msg  string
}

func (e HTTPError) Error() string {
  return fmt.Sprintf("HTTP Error: %d - %s", e.Code, e.Msg)
}

func main() {
  // 发送请求并捕获响应
  resp, err := http.Get("https://example.com")
  if err != nil {
    fmt.Println(err)
    return
  }

  if resp.StatusCode != http.StatusOK {
    // 创建自定义错误
    err = HTTPError{Code: resp.StatusCode, Msg: "请求失败"}
    fmt.Println(err)
  }
}

Practical case

The following is the use of http.Response .StatusCode Practical example of verifying status code:

Suppose you are developing an API that uses HTTP GET to retrieve data from a database. You need to verify the response status code to ensure that the request completed successfully:

func GetUserData(userID int) (UserData, error) {
  resp, err := http.Get(fmt.Sprintf("https://myapi.com/users/%d", userID))
  if err != nil {
    return UserData{}, err
  }

  if resp.StatusCode != http.StatusOK {
    return UserData{}, fmt.Errorf("请求失败: %d", resp.StatusCode)
  }

  // 解析响应并返回数据
}

By validating the response status code, you can ensure that data is only returned if the server successfully processed the request.

The above is the detailed content of How to verify HTTP response status code in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn