SoFunction
Updated on 2025-03-05

Detailed explanation of how to make Http calls in Go

Preface

Whether it is microservices or monolithic architectures, services have time to communicate with each other, and the most direct way of communication isHTTPCalling, this article will introduceGoHow to do it in languageHTTPCall and give examples.

Pre-knowledge

HTTPThe call needs to be passedhttpIn the bagClientIn the structureDoMethods are implemented, so one needs to be declared firstClientStructural variable, this structure can set timeout and other configurations.

For a requestURL, query parameters, requestmethodetc., requiredhttpIn the bagRequestStructure de-encapsulation. We can passNewRequestWithContextorNewRequestGet a basic functionRequestStructure pointer variable.

NewRequestWithContext(ctx , method, url string, body ) (*Request, error)

  • parameterctxforContextThe interface type, arbitrarily implementedContextAll custom types of interfaces can be passed as this parameter.
  • parametermethodforHTTPMethod parameters, optional values ​​areGETPOSTDELETEPUTwait.
  • parameterurlThe request path for the interface.
  • parameterbody, is the request body parameter.

pass(req)After the method is called, the return value is(*Response, error), the first is the response structure parameter, and the second is the error parameter. Read byResponseofbodyThe value of , can obtain the response body of the interface.

GET Request

import (
    "context"
    "fmt"
    "io"
    "net/http"
)

func main() {
    client := {}
    request, err := ((), , "http://localhost:8080/user?name=tom", nil)
    if err != nil {
        return
    }
    ("headerParam", "header")
    resp, err := (request)
    if err != nil {
        (err)
        return
    }
    bytes, err := ()
    if err != nil {
        return
    }
    defer ()
    (string(bytes)) // {"code":0,"data":{"list":[{"name":"Xiao Ming","age":20},{"name":"Xiaohong","age":18}]},"message":"success"}}
  • When you need to carry query parameters, you can directly splice them inurlabove the string.
  • headerParameters can be passed through the request structureHeaderFieldssetMethod oraddMethod to set.
  • The HTTP request response code can be passedResponseofStatusCodefields for viewing.
  • After the interface request is successful, passMethod, readResponse body information.
  • Except directly inurlSplicing onqueryWe can also add parameters in the following waysqueryparameter:
params := {}
rawUrl, err := ("http://localhost:8080/user")
if err != nil {
	return
}
("name", "tom")
 = ()
u := ()

passStructuralsetMethod setting query parameters,urlpassThe function generates aURLStructure pointer variable, = ()Through this line of codequeryParameters andurlMake binding, and finally passString()Method willurlConvert tostringtype.

summary

This article introduces how to make HTTP calls in Go language, which need to be passedhttpIn the bagClientStructural variable, call its methodDoconductHTTPBefore calling HTTP, you need to pass the http packageRequestStructure encapsulates request path and request parameters. Last passedGETThe request case tellsqueryParameters andheaderHow to set parameters and how to obtain the response body.

This is the end of this article about how to make Http calls in Go. For more relevant content on Http calls in Go, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!