Home  >  Article  >  Backend Development  >  How to request soap in golang

How to request soap in golang

PHPz
PHPzOriginal
2023-04-25 10:30:41809browse

Go language is an open source, fast, lightweight programming language. It supports high concurrency, multi-threading, cross-platform and other features, so it is widely used in network development. In most cases, we need to interact with other systems through HTTP requests. However, some systems do not support HTTP protocol, but use SOAP protocol (Simple Object Access Protocol). So, how to send a SOAP request in Go language? This article will introduce this issue.

Prerequisite knowledge

Before starting to talk about how to send SOAP requests, you need to understand several necessary knowledge points.

SOAP Protocol

SOAP is an XML language-based protocol used to exchange data in a distributed environment. It defines message formats and rules for description and communication, allowing applications to send and receive messages through protocols such as HTTP and SMTP. SOAP messages mainly consist of three parts: envelope, header, and body.

  • envelope: The root element of the SOAP message, which contains all message elements.
  • Header: Optional, used to pass information unrelated to the actual data, such as security information.
  • body: Contains the actual transmitted data.

The format of the SOAP message is as follows:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Header>
        <!-- 可选的头部信息 -->
    </soap:Header>
    <soap:Body>
        <!-- 实际数据 -->
    </soap:Body>
</soap:Envelope>

Net/http library of Go language

net/http is one of the standard libraries provided by Go language. Used to handle HTTP requests and responses. Through this library, we can easily implement network operations of HTTP server and HTTP client. For HTTP requests, you need to pay attention to the following key parameters:

  • URL: the target address of the request.
  • Method: Request method, including GET, POST, PUT, DELETE, etc.
  • Headers: Request header information, such as Content-Type, User-Agent, etc.
  • Body: The actual data requested.

Steps to send SOAP requests

With the previous knowledge base, we can now learn step by step how to send SOAP requests in Go language. The specific steps are as follows:

  • Confirm the target address

First, we need to confirm the address and port number of the target server. After determining this information, we can build the request URL.

  • Confirm the request method and request header

Next, we need to confirm the SOAP request method and request header information. SOAP requests need to encapsulate XML document type data into HTTP requests, so we need to set parameters such as Content-Type and SOAPAction in the request header. The specific request header information needs to be determined according to the interface document.

  • Constructing the request message

After confirming the request method and request header information, we need to construct the request message. The request message contains all elements of the SOAP message: Envelope, Header, Body, etc. Among them, the content in the Body element is the actual data. You can use encoding/xml or string to construct the request message. Here we use encoding/xml method.

  • Send a request

After building the request message, we can use the client in the net/http library to send the request. The specific method is as follows:

resp, err := client.Do(req)

Among them, client is the HTTP client and req is the HTTP request. The Do method is used to send HTTP requests and return HTTP responses. It should be noted that the client needs to close the connection after use.

  • Handling the response

Finally, we need to handle the HTTP response. Extract the actual data from the response and parse it. Here, we need to determine the data content and format that need to be extracted and parsed based on the interface document.

Sample Code

Below, we take an actual SOAP request as an example to show the sample code of how to use Go language to send a SOAP request. Here, we are using the interface of an e-commerce platform, with slight modifications to the specific situation.

package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Envelope struct {
    XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
    Header  *Header  `xml:",omitempty"`
    Body    *Body
}

type Header struct {
    // 这里可以定义需要的头部信息
}

type Body struct {
    XMLName xml.Name `xml:"Body"`
    Req     *Req
}

type Req struct {
    XMLName xml.Name `xml:"http://www.example.com/ OrderRequest"`
    Order   *Order
}

type Order struct {
    XMLName xml.Name `xml:"Order"`
    // 这里定义Order元素的子元素
}

func main() {
    // 确认目标地址
    url := "http://example.com/path/to/server"
    
    // 确认请求方法和请求头部信息
    soapAction := "http://www.example.com/OrderRequest"
    contentType := "text/xml;charset=utf-8"
    
    // 构建请求消息
    order := &Order{
        // 这里为Order元素的子元素赋值
    }
    req := &Req{
        Order: order,
    }
    body := &Body{
        Req: req,
    }
    envelope := &Envelope{
        Body: body,
    }
    data, err := xml.Marshal(envelope)
    if err != nil {
        fmt.Println("marshal error:", err)
        os.Exit(1)
    }
    
    // 发送请求
    client := &http.Client{}
    reqBody := bytes.NewBuffer(data)
    req, err := http.NewRequest("POST", url, reqBody)
    if err != nil {
        fmt.Println("create request error:", err)
        os.Exit(1)
    }
    req.Header.Set("Content-Type", contentType)
    req.Header.Set("SOAPAction", soapAction)
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("send request error:", err)
        os.Exit(1)
    }
    defer resp.Body.Close()
    
    // 处理响应
    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("read response body error:", err)
        os.Exit(1)
    }
    
    // 这里对respBody进行解析,提取需要的数据
}

Summary

Sending SOAP requests in Go language may be a bit cumbersome, but as long as we understand some basic knowledge and precautions, we can successfully complete the request. These knowledge points are particularly important when you need to access an interface that only supports the SOAP protocol. I hope this article can be helpful to readers.

The above is the detailed content of How to request soap 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