SoFunction
Updated on 2025-03-04

golang http request encapsulation code

Create utils folder in GOPATH Place these two files

package utils 
import (
 "crypto/tls"
 "encoding/json"
 "errors"
 "fmt"
 "io/ioutil"
 "net/http"
 "net/url"
 "strings"
 "sync"
) 
var (
 GET_METHOD = "GET"
 POST_METHOD = "POST"
 SENDTYPE_FROM = "from"
 SENDTYPE_JSON = "json"
) 
type HttpSend struct {
 Link  string
 SendType string
 Header map[string]string
 Body  map[string]string
 
} 
func NewHttpSend(link string) *HttpSend {
 return &HttpSend{
  Link:  link,
  SendType: SENDTYPE_FROM,
 }
} 
func (h *HttpSend) SetBody(body map[string]string) {
 ()
 defer ()
  = body
} 
func (h *HttpSend) SetHeader(header map[string]string) {
 ()
 defer ()
  = header
} 
func (h *HttpSend) SetSendType(send_type string) {
 ()
 defer ()
  = send_type
} 
func (h *HttpSend) Get() ([]byte, error) {
 return (GET_METHOD)
} 
func (h *HttpSend) Post() ([]byte, error) {
 return (POST_METHOD)
} 
func GetUrlBuild(link string, data map[string]string) string {
 u, _ := (link)
 q := ()
 for k, v := range data {
  (k, v)
 }
  = ()
 return ()
} 
func (h *HttpSend) send(method string) ([]byte, error) {
 var (
  req  *
  resp  *
  client 
  send_data string
  err  error
 ) 
 if len() > 0 {
  if () == SENDTYPE_JSON {
   send_body, json_err := ()
   if json_err != nil {
    return nil, json_err
   }
   send_data = string(send_body)
  } else {
   send_body := {}
   send_body.ParseForm()
   for k, v := range  {
    send_body.(k, v)
   }
   send_data = send_body.()
  }
 } 
 //Ignore https certificate  = &{
  TLSClientConfig: &{InsecureSkipVerify: true},
 } 
 req, err = (method, , (send_data))
 if err != nil {
  return nil, err
 }
 defer ()
 
 //Set the default header if len() == 0 {
  //json
  if () == SENDTYPE_JSON {
    = map[string]string{
    "Content-Type": "application/json; charset=utf-8",
   }
  } else { //form
    = map[string]string{
    "Content-Type": "application/x-www-form-urlencoded",
   }
  }
 } 
 for k, v := range  {
  if (k) == "host" {
    = v
  } else {
   (k, v)
  }
 } 
 resp, err = (req)
 if err != nil {
  return nil, err
 }
 defer ()
 
 if  !=  {
  return nil, (("error http code :%d", ))
 } 
 return ()
}

http_test.go

package utils 
import (
 "testing"
) 
func Test_Get(t *) {
 h := NewHttpSend(GetUrlBuild("http://127.0.0.1/", map[string]string{"name": "xiaochuan"}))
 _, err := ()
 if err != nil {
 ("Request Error:", err)
 } else {
 ("Return normally")
 }
} 
func Test_Post(t *) {
 h := NewHttpSend("http://127.0.0.1/")
 (map[string]string{"name": "xiaochuan"})
 _, err := ()
 if err != nil {
 ("Request Error:", err)
 } else {
 ("Return normally")
 }
} 
func Test_Json(t *) {
 h := NewHttpSend("http://127.0.0.1/")
 ("JSON")
 (map[string]string{"name": "xiaochuan"})
 _, err := ()
 if err != nil {
 ("Request Error:", err)
 } else {
 ("Return normally")
 }
} 
func Benchmark_GET(b *) {
 for i := 0; i < ; i++ {
 h := NewHttpSend(GetUrlBuild("http://127.0.0.1/", map[string]string{"name": "xiaochuan"}))
 _, err := ()
 if err != nil {
 ("Request Error:", err)
 } else {
 ("Return normally")
 }
 }
}

Supplement: Several common situations in golang for sending http requests

Organize various http sending methods in golang

In some initial projects, many places used golang to send http requests, and then some processing of the results received by the requests. The mode used is also relatively fixed. Here I will sort out the centralized http sending method, first record so much, and then add it bit by bit.

The most basic scenario

Method 1 Use

Generate -> Regenerate -> Submit the request afterwards: (request) -> Processing returns the result. Each step of the process can set some specific parameters. The following is the simplest and most basic example:

//question ???Redirect stdout to response information?  ?  ?package main 
import (
 "fmt"
 "io"
 "net/http"
 "os"
) 
func main() {
 //Generate client parameters as default client := &{} 
 //Generate the URL to access url := ""  
 //Submit a request reqest, err := ("GET", url, nil) 
 if err != nil {
 panic(err)
 } 
 // Processing returns result response, _ := (reqest) 
 // Position the result to standard output, you can also print it out directly or locate it to other places for corresponding processing stdout := 
 _, err = (stdout, ) 
 //Returned status code status :=  
 (status) 
}

Method 2: Create a client, and then use /post..

The client structure itself also has some methods to send APIs, such as,..., etc. Basically, the main http request types are covered. Usually, if there is no special configuration, it is fine. In fact, the client's get or post method is also an encapsulation of the method. It also adds additional ("Content-Type", bodyType) to it. Generally, it is OK.

Method three http. Get/Post..

When implementing the specific implementation, the previously mentioned pattern is still adopted, and a default client is created and the method is called.

Detailed description of each step

Parameter configuration when generating client

The most common parameter is the settings of the client when sending information using https. If no information is added when generating the client, the default value will be used. Specific information includes:

 Transport RoundTripper
 CheckRedirect func(req *Request, via []*Request) error
 Jar CookieJar
 Timeout 

The first parameter is a RoundTripper interface, which contains a RoundTrip function, which specifies some basic mechanisms for http requests.

There are many parameters involved. If not specified, the default DefaultTransport parameter will be used, which contains some default request time and proxy mechanism.

There are many specific parameters involved, some of which have not been used before, such as my handshake time. The most commonly used parameters are https: TLSClientConfig, which is a * type, and there are still many parameters involved. One basic one is the use case, for example, the following is the only way to formulate the certificates used by rooca and client side in the configuration.

Usually when sending https requests, the previous parameters can be processed in the following way:

pool := ()
 caCertPath := "certs/cert_server/" 
 caCrt, err := (caCertPath)
 if err != nil {
 ("ReadFile err:", err)
 return
 }
 (caCrt) 
 cliCrt, err := tls.LoadX509KeyPair("certs/cert_server/", "certs/cert_server/")
 if err != nil {
 ("Loadx509keypair err:", err)
 return
 } 
 tr := &{
 TLSClientConfig: &{
 RootCAs:  pool,
 Certificates: []{cliCrt},
 },
 }
 client := &{Transport: tr}

Parameter configuration when generating request

When generating a request, the main ones are several basic parameters. The NewRequest function has three basic parameters. The first one is the request type, GET, POST, PUT, etc. It should be set to capitalize. The second parameter is the URL to be accessed by the request, and the third parameter is the content in the requested body, which needs to be a type.

The interface you notice is a Read method. The types that implement Read method should be returned as a return. The specific function of the Read(p []byte) (n int, err error) function is to read the content of the length of len(p) into p, and return the read length and error information.

Usually, it is to use a function to convert a string type into a type, or a function to convert the []byte type into a type.

In addition, you can add some additional information to the request header, such as the type of the requested body and the information of the token in the following example.

("Content-Type", "application/x-www-form-urlencoded")

("Authorization", "qwertyuiopasdfghjklzxcvbnm1234567890")

For example, to simulate form submission, you can set the submitted type to type and then encode:

// use map as struct
 var clusterinfo = {}
 //var clusterinfo = map[string]string{}
 ("userName", user)
 ("password", pw)
 ("cloudName", clustername)
 ("masterIp", masterip)
 ("cacrt", string(caCrt)) 
 data := () 
 url := "https://10.10.105.124:8443/user/checkAndUpdate"
 reqest, err := ("POST", url, (data))

The most common situation is to send a json file, and the type of the header can be set to:

"Content-Type", "application/json; charset=utf-8"

Just set the rest of the parts in the same way as before and send the submission.

There are still many attributes of the type of request, so sort them out slowly.

Processing of generated response results

Generally, after the client is built, the client request must be submitted using the (request) method, and a *Response type will be returned. There are generally more parameters in the response. The most we need is usually the Body parameter. Generally, body, _ := () will be converted into []byte type and returned, and then other processing will be performed.

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.