Skip to content

Commit

Permalink
Accept message handler
Browse files Browse the repository at this point in the history
To allow the application to handle the incoming requests the way it wants
(log/save the data) we make the handler function accept the a function that
gets the data from the request.
  • Loading branch information
noplisu committed Jun 13, 2024
1 parent 399e072 commit 2bddda0
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 53 deletions.
16 changes: 15 additions & 1 deletion cmd/gobl.fatturapa/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ func (c *serverOpts) runE(cmd *cobra.Command, args []string) error {
ClientAuth: clientAuth,
}

err = sdi.RunServer(config, sdi.MessageHandler)
messageHandler := sdi.MessageHandler(handleRequest)

err = sdi.RunServer(config, messageHandler)
if err != nil {
return fmt.Errorf("server error: %w", err)
}
Expand Down Expand Up @@ -122,6 +124,18 @@ func loadTLSCert(publicCertPEM, privateKeyPEM []byte) (tls.Certificate, error) {
return serverTLSCert, nil
}

func handleRequest(env *sdi.SDIEnvelope) {
if env.Body.FileSubmissionMetadata != nil {
log.Printf("parsing MetadatiInvioFile:\n")
}
if env.Body.NonDeliveryNotificationMessage != nil {
log.Printf("parsing NotificaMancataConsegna:\n")
}
if env.Body.InvoiceTransmissionCertificate != nil {
log.Printf("parsing AttestazioneTrasmissioneFattura:\n")
}
}

func loadCertPoolFromPEM(caCertPEM []byte) (*x509.CertPool, error) {
caCertPool, err := x509.SystemCertPool()
if err != nil {
Expand Down
16 changes: 5 additions & 11 deletions sdi/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ import (
"encoding/xml"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"strings"

resty "github.com/go-resty/resty/v2"
)

// HandleSOAPRequest
type HandleSOAPRequest func(*SDIEnvelope)

// SDIEnvelope defines messages received by
type SDIEnvelope struct {
XMLName xml.Name `xml:"Envelope"`
Expand Down Expand Up @@ -61,7 +63,7 @@ func parseMultipartResponse(resp *resty.Response, response interface{}) error {
return nil
}

func ParseMessage(body io.ReadCloser) error {
func ParseMessage(body io.ReadCloser, handler HandleSOAPRequest) error {
data, err := io.ReadAll(body)
if err != nil {
return err
Expand All @@ -71,15 +73,7 @@ func ParseMessage(body io.ReadCloser) error {
if err != nil {
return err
}
if env.Body.FileSubmissionMetadata != nil {
log.Printf("parsing MetadatiInvioFile:\n")
}
if env.Body.NonDeliveryNotificationMessage != nil {
log.Printf("parsing NotificaMancataConsegna:\n")
}
if env.Body.InvoiceTransmissionCertificate != nil {
log.Printf("parsing AttestazioneTrasmissioneFattura:\n")
}
handler(env)

return nil
}
18 changes: 15 additions & 3 deletions sdi/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,18 @@ import (
"github.com/stretchr/testify/assert"
)

func handlerFunc(env *sdi.SDIEnvelope) {
if env.Body.FileSubmissionMetadata != nil {
log.Printf("parsing MetadatiInvioFile:\n")
}
if env.Body.NonDeliveryNotificationMessage != nil {
log.Printf("parsing NotificaMancataConsegna:\n")
}
if env.Body.InvoiceTransmissionCertificate != nil {
log.Printf("parsing AttestazioneTrasmissioneFattura:\n")
}
}

func TestParseMessage(t *testing.T) {
t.Run("parse MetadatiInvioFile", func(t *testing.T) {
var buf bytes.Buffer
Expand All @@ -36,7 +48,7 @@ func TestParseMessage(t *testing.T) {
`</soapenv:Envelope>`
reader := strings.NewReader(message)

sdi.ParseMessage(io.NopCloser(reader))
sdi.ParseMessage(io.NopCloser(reader), handlerFunc)

assert.Contains(t, buf.String(), "parsing MetadatiInvioFile")
})
Expand Down Expand Up @@ -64,7 +76,7 @@ func TestParseMessage(t *testing.T) {
`</soapenv:Envelope>`
reader := strings.NewReader(message)

sdi.ParseMessage(io.NopCloser(reader))
sdi.ParseMessage(io.NopCloser(reader), handlerFunc)

assert.Contains(t, buf.String(), "parsing NotificaMancataConsegna")
})
Expand Down Expand Up @@ -96,7 +108,7 @@ func TestParseMessage(t *testing.T) {
`</soapenv:Envelope>`
reader := strings.NewReader(message)

sdi.ParseMessage(io.NopCloser(reader))
sdi.ParseMessage(io.NopCloser(reader), handlerFunc)

assert.Contains(t, buf.String(), "parsing AttestazioneTrasmissioneFattura")
})
Expand Down
78 changes: 40 additions & 38 deletions sdi/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,48 +9,50 @@ import (
)

// MessageHandler processes SOAP requests from SdI (Sistema di Interscambio)
func MessageHandler(w http.ResponseWriter, req *http.Request) {
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
log.Printf("Failed to dump incoming request: %s\n", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
log.Printf("Incoming request:\n%s", requestDump)
func MessageHandler(handler HandleSOAPRequest) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
log.Printf("Failed to dump incoming request: %s\n", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
log.Printf("Incoming request:\n%s", requestDump)

err = ParseMessage(req.Body)
if err != nil {
log.Printf("Failed to parse body: %s\n", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = ParseMessage(req.Body, handler)
if err != nil {
log.Printf("Failed to parse body: %s\n", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

responseBody := []byte(soapEmptyResponse())
response := &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Proto: "HTTP/2.0",
ProtoMajor: 2,
ProtoMinor: 0,
Body: io.NopCloser(bytes.NewReader(responseBody)),
ContentLength: int64(len(responseBody)),
Header: make(http.Header),
}
// contentType := http.DetectContentType(responseBody)
response.Header.Set("Content-Type", "application/soap+xml")
responseBody := []byte(soapEmptyResponse())
response := &http.Response{
Status: "200 OK",
StatusCode: http.StatusOK,
Proto: "HTTP/2.0",
ProtoMajor: 2,
ProtoMinor: 0,
Body: io.NopCloser(bytes.NewReader(responseBody)),
ContentLength: int64(len(responseBody)),
Header: make(http.Header),
}
// contentType := http.DetectContentType(responseBody)
response.Header.Set("Content-Type", "application/soap+xml")

responseDump, err := httputil.DumpResponse(response, true)
if err != nil {
log.Printf("Failed to dump outgoing response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
log.Printf("Outgoing response:\n%s", responseDump)
responseDump, err := httputil.DumpResponse(response, true)
if err != nil {
log.Printf("Failed to dump outgoing response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
log.Printf("Outgoing response:\n%s", responseDump)

err = responseToWriter(w, response)
if err != nil {
log.Printf("Failed to send response: %v", err)
return
err = responseToWriter(w, response)
if err != nil {
log.Printf("Failed to send response: %v", err)
return
}
}
}

Expand Down

0 comments on commit 2bddda0

Please sign in to comment.