soap

package
v1.67.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 15 Imported by: 0

README

Package soap

Пакет soap предоставляет инструменты для работы с SOAP-сервисами: обработка запросов, валидация данных, генерация ошибок в формате SOAP Fault, а также интеграция с метриками и логированием.

Types

ActionMux

Мультиплексор для маршрутизации SOAP-запросов на основе заголовка SOAPAction.

Methods:

NewActionMux() *ActionMux

Создает новый мультиплексор.

(m *ActionMux) Handle(actionUri string, handler http.Handler) *ActionMux

Регистрирует обработчик для указанного SOAPAction.

(m *ActionMux) ServeHTTP(writer http.ResponseWriter, request *http.Request)

Обрабатывает запрос, определяя действие через заголовок SOAPAction, и вызывает соответствующий обработчик. При отсутствии действия или неизвестном SOAPAction возвращает SOAP Fault.

RequestExtractor

Извлекает данные из SOAP-конверта и валидирует их с помощью объекта, реализующего интерфейс Validator.

Methods:

(j RequestExtractor) Extract(_ context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)

Десериализация XML и проверка данных через Validator.

ResponseMapper

Формирует SOAP-ответ из данных, добавляя заголовки и сериализуя в XML.

Methods:

(j ResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error

Упаковка результата в SOAP-конверт.

Functions

DefaultWrapper(logger log.Logger, logMiddleware endpoint.LogMiddleware, restMiddlewares ...http.Middleware) endpoint.Wrapper

Создает обертку для обработчиков с предустановленными middleware:

  • Ограничение размера тела запроса (по умолчанию 64 МБ).
  • Добавление RequestId.
  • Логирование и метрики.
  • Трейсинг.
  • Обработка ошибок через ErrorHandler.
ErrorHandler(logger log.Logger) http2.Middleware

Middleware для перехвата ошибок, их логирования и преобразования в SOAP Fault.

Usage

Default usage flow
package main

import (
	"context"
	"encoding/xml"
	"log"
	"net/http"

	"github.com/txix-open/isp-kit/http/endpoint/httplog"
	"github.com/txix-open/isp-kit/http/soap"
	log2 "github.com/txix-open/isp-kit/log"
)

type UserRequest struct {
	XMLName xml.Name `xml:"UserRequest"`
	Name    string   `xml:"name"`
}

func main() {
	logger, err := log2.New()
	if err != nil {
		log.Fatal(err)
	}
	mux := soap.NewActionMux()

	wrapper := soap.DefaultWrapper(logger, httplog.Log(logger, true))
	handler := wrapper.Endpoint(func(ctx context.Context, req UserRequest) {
		/* put here business logic */
	})
	mux.Handle("CreateUser", handler)

	http.ListenAndServe(":8080", mux)
}

Documentation

Overview

Package soap provides SOAP message handling for XML-based web services. It implements the SOAP 1.1 protocol with support for envelopes, headers, bodies, and faults.

Index

Constants

View Source
const (
	// ActionHeader is the HTTP header name for the SOAP action.
	ActionHeader = "SOAPAction"
)
View Source
const (
	// ContentType is the standard SOAP content type.
	ContentType = `text/xml; charset="utf-8"`
)

Variables

This section is empty.

Functions

func DefaultWrapper

func DefaultWrapper(logger log.Logger, logMiddleware endpoint.LogMiddleware, restMiddlewares ...http.Middleware) endpoint.Wrapper

DefaultWrapper creates a pre-configured endpoint.Wrapper for SOAP services. It includes request logging, metrics collection, tracing, error handling, and recovery. The default maximum request body size is 64MB.

func ErrorHandler

func ErrorHandler(logger log.Logger) http2.Middleware

ErrorHandler is a middleware that logs errors and writes SOAP fault responses. It uses the error's WriteError method if available; otherwise, it returns a generic server fault to hide implementation details.

Types

type ActionMux

type ActionMux struct {
	// contains filtered or unexported fields
}

ActionMux routes SOAP requests based on the SOAPAction HTTP header. It provides a simple multiplexer for handling multiple SOAP operations.

func NewActionMux

func NewActionMux() *ActionMux

NewActionMux creates a new ActionMux with an empty handler map.

func (*ActionMux) Handle

func (m *ActionMux) Handle(actionUri string, handler http.Handler) *ActionMux

Handle registers a handler for the specified SOAP action URI. It panics if a handler for the action is already registered. Returns the ActionMux for fluent chaining.

func (*ActionMux) ServeHTTP

func (m *ActionMux) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP implements the http.Handler interface and routes requests based on SOAPAction. It returns a SOAP fault if the SOAPAction header is missing or the action is unknown. The action is added to the request context for logging purposes.

type Body

type Body struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`

	Content any `xml:",omitempty"`

	Fault *Fault `xml:",omitempty"`
	// contains filtered or unexported fields
}

Body represents a SOAP body containing the message content or fault. It supports both regular content and SOAP faults, with WS-I compliance validation.

func (*Body) UnmarshalXML

func (b *Body) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error

UnmarshalXML decodes a SOAP body from XML, handling both content and faults. It enforces WS-I compliance by rejecting multiple elements inside the SOAP body.

type Envelope

type Envelope struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`

	Header *Header
	Body   Body
}

Envelope represents a SOAP envelope containing a header and body. It is the root element of a SOAP message.

type Fault

type Fault struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault"`

	Code   string `xml:"faultcode,omitempty"`
	String string `xml:"faultstring,omitempty"`
	Actor  string `xml:"faultactor,omitempty"`
	Detail any    `xml:"detail,omitempty"`
}

Fault represents a SOAP fault containing error information. It follows the SOAP 1.1 fault structure with code, string, actor, and optional detail. nolint:errname

func (Fault) Error

func (f Fault) Error() string

Error returns the fault string as the error message.

func (Fault) WriteError

func (f Fault) WriteError(w http.ResponseWriter) error

WriteError writes the fault as a SOAP XML response to the http.ResponseWriter. It sets the Content-Type to text/xml and the HTTP status code to 500.

type Header struct {
	XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Header"`

	Items []any `xml:",omitempty"`
}

Header represents a SOAP header containing optional metadata.

type RequestExtractor

type RequestExtractor struct {
	Validator Validator
}

RequestExtractor extracts and validates SOAP request bodies from XML. It decodes the SOAP envelope, extracts the body content, and validates it.

func (RequestExtractor) Extract

func (j RequestExtractor) Extract(_ context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)

Extract decodes the SOAP envelope from the reader and extracts the body content into a reflect.Value of the specified type. It validates the decoded value and returns a SOAP fault if validation fails.

func (RequestExtractor) ExtractV2 added in v1.61.0

func (j RequestExtractor) ExtractV2(ctx context.Context, reader io.Reader, ptr any) error

ExtractV2 decodes the SOAP envelope from the reader and extracts the body content into the provided pointer. It validates the decoded value and returns a SOAP fault if validation fails.

type ResponseMapper

type ResponseMapper struct {
}

ResponseMapper maps response objects to SOAP XML format. It wraps the result in a SOAP envelope and sets the appropriate content type.

func (ResponseMapper) Map

func (j ResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error

Map encodes the result as a SOAP envelope and writes it to the http.ResponseWriter. It sets the Content-Type to text/xml and includes the request ID in response headers if available.

type Validator

type Validator interface {
	ValidateToError(v any) error
}

Validator validates a value and returns an error if validation fails.

Directories

Path Synopsis
Package client provides a SOAP client for invoking SOAP web services.
Package client provides a SOAP client for invoking SOAP web services.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL