Home > Article > Backend Development > How to verify HTTP response status code in Golang?
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.
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!