From dd3f6769f6f2eb37c0ae513e2ce6fbfee9c5b90e Mon Sep 17 00:00:00 2001 From: zhiqiang feng Date: Wed, 8 Jul 2026 15:17:07 +0800 Subject: [PATCH] refactor ciims proxy transport and handlers --- .gitignore | 14 +++ cmd/main/main.go | 205 ++++++++++++++++++++++++++++++--------- cmd/main/main_test.go | 119 +++++++++++++++++++++++ go.mod | 39 +++++++- go.sum | 125 +++++++++++++++--------- internal/codec.go | 77 ++++++++------- internal/handler_test.go | 174 +++++++++++++++++++++++++++++++++ internal/http.go | 90 +++++++++++++---- 8 files changed, 689 insertions(+), 154 deletions(-) create mode 100644 .gitignore create mode 100644 cmd/main/main_test.go create mode 100644 internal/handler_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed5e7ae --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Binaries +ciimsproxy +/main +*.exe +*.test + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store diff --git a/cmd/main/main.go b/cmd/main/main.go index cf07bb3..da61270 100644 --- a/cmd/main/main.go +++ b/cmd/main/main.go @@ -1,97 +1,206 @@ package main import ( + "errors" + "fmt" + "log" "net/http" "os" + "strconv" "github.com/gin-gonic/gin" - "github.com/labstack/gommon/log" "gzzn.com/mini/ciimsproxy/internal" ) const ( - servicePrefix string = "/services/ExchangeService" - // defaultURL string = "http://localhost:8080" - //defaultURL string = "http://192.168.10.96:8080" + servicePrefix string = "/services/ExchangeService" + defaultTimeout = 240 + maxMsgLen = 1048576 // 1MB + maxCount = 1000 ) -var defaultURL = "" +type Config struct { + ServerURL string + Listen string + Timeout int + Client *internal.Client +} + +type App struct { + config Config +} func main() { - defaultURL = os.Getenv("CIIMS_SERVER") - listen := os.Getenv("PROXY_LISTEN") - if listen == "" { - listen = ":9090" + config, err := loadConfig() + if err != nil { + log.Printf("[ERROR] configuration error: %v", err) + os.Exit(1) } - println("use ciims : " + defaultURL) + + log.Printf("use ciims: %s", config.ServerURL) + r := newRouter(config) + log.Printf("Starting ciims proxy for %s", config.ServerURL) + log.Printf("timeout: %d", config.Timeout) + if err := r.Run(config.Listen); err != nil { + log.Printf("[ERROR] server failed: %v", err) + os.Exit(1) + } +} + +func loadConfig() (Config, error) { + config := Config{ + ServerURL: os.Getenv("CIIMS_SERVER"), + Listen: os.Getenv("PROXY_LISTEN"), + Timeout: defaultTimeout, + } + t, err := getIntEnv("CIIMS_TIMEOUT") + if err != nil { + return Config{}, err + } + if t > 0 { + config.Timeout = t + } + if config.Listen == "" { + config.Listen = ":9090" + } + config.Client, err = internal.NewClient(config.Timeout) + if err != nil { + return Config{}, err + } + return config, nil +} + +func newRouter(config Config) *gin.Engine { + app := &App{config: config} r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) - r.POST("/send", sendMessage) - r.POST("/receive", receiveMessage) - // r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") - log.Info("Starting ciims proxy for : " + defaultURL) - r.Run(listen) + r.POST("/send", app.sendMessage) + r.POST("/receive", app.receiveMessage) + return r } -func sendMessage(c *gin.Context) { +func (a *App) sendMessage(c *gin.Context) { + // Limit request body size + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxMsgLen) + var message struct { - URL string `json:"url" ` + URL string `json:"url"` User string `json:"user" binding:"required"` Pass string `json:"pass" binding:"required"` Event string `json:"event" binding:"required"` - Priority int `json:"priority" ` + Priority int `json:"priority"` Val bool `json:"val"` Msg string `json:"msg" binding:"required"` } - err := c.Bind(&message) - if err == nil { - msg := internal.CreateSend(message.User, message.Pass, - message.Priority, message.Event, message.Val, message.Msg) - url := getURL(message.URL) - resp, err := internal.Send(url, msg) - errMsg := internal.GetErrMsg(resp) - if err == nil { - c.JSON(http.StatusOK, gin.H{"error": errMsg}) - } else { - c.JSON(http.StatusInternalServerError, gin.H{"error": errMsg}) - } - } else { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if err := c.ShouldBind(&message); err != nil { + a.handleBindError(c, err) + return } + msg := internal.CreateSend(message.User, message.Pass, + message.Priority, message.Event, message.Val, message.Msg) + url := a.getURL(message.URL) + resp, err := a.config.Client.Send(url, msg) + if err != nil { + a.handleSendError(c, "send", resp, err) + return + } + errMsg := resp.ErrorMessage() + if len(errMsg) > 0 { + log.Printf("[ERROR] SOAP fault: %s", errMsg) + c.JSON(http.StatusInternalServerError, gin.H{"error": errMsg}) + return + } + c.JSON(http.StatusOK, gin.H{"error": ""}) } -func receiveMessage(c *gin.Context) { +func (a *App) receiveMessage(c *gin.Context) { + // Limit request body size + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxMsgLen) + var message struct { - URL string `json:"url" ` + URL string `json:"url"` User string `json:"user" binding:"required"` Pass string `json:"pass" binding:"required"` Count int `json:"count" binding:"required"` } - err := c.Bind(&message) - if err == nil { - msg := internal.CreateReceive(message.User, message.Pass, message.Count) - url := getURL(message.URL) - resp, err := internal.Send(url, msg) - if err == nil { - c.JSON(http.StatusOK, gin.H{"msgs": internal.GetMsgs(resp)}) - } else { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } - } else { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if err := c.ShouldBind(&message); err != nil { + a.handleBindError(c, err) + return } + + if message.Count < 1 || message.Count > maxCount { + c.JSON(http.StatusBadRequest, gin.H{"error": "count must be between 1 and " + strconv.Itoa(maxCount)}) + return + } + + msg := internal.CreateReceive(message.User, message.Pass, message.Count) + url := a.getURL(message.URL) + resp, err := a.config.Client.Send(url, msg) + if err != nil { + a.handleSendError(c, "receive", resp, err) + return + } + if errMsg := resp.ErrorMessage(); errMsg != "" { + log.Printf("[ERROR] SOAP fault: %s", errMsg) + c.JSON(http.StatusInternalServerError, gin.H{"error": errMsg}) + return + } + c.JSON(http.StatusOK, gin.H{"msgs": resp.Messages()}) + } -func getURL(url string) string { +func (a *App) getURL(url string) string { var result string if len(url) > 0 { result = url + servicePrefix } else { - result = defaultURL + servicePrefix + result = a.config.ServerURL + servicePrefix } return result } + +func (a *App) handleBindError(c *gin.Context, err error) { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": err.Error()}) + return + } + log.Print(err.Error()) + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) +} + +func (a *App) handleSendError(c *gin.Context, operation string, resp *internal.CIIMSResponse, err error) { + if resp != nil { + if errMsg := resp.ErrorMessage(); errMsg != "" { + log.Printf("[ERROR] SOAP fault: %s", errMsg) + c.JSON(http.StatusInternalServerError, gin.H{"error": errMsg}) + return + } + } + var statusErr *internal.HTTPStatusError + if errors.As(err, &statusErr) { + if errMsg := internal.GetErrMsg(statusErr.Body); errMsg != "" { + log.Printf("[ERROR] SOAP fault: %s", errMsg) + c.JSON(http.StatusInternalServerError, gin.H{"error": errMsg}) + return + } + } + log.Printf("[ERROR] %s failed: %v", operation, err) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) +} + +func getIntEnv(key string) (int, error) { + val := os.Getenv(key) + if val == "" { + return 0, nil + } + ret, err := strconv.Atoi(val) + if err != nil { + return 0, fmt.Errorf("invalid %s value %q: must be an integer", key, val) + } + return ret, nil +} diff --git a/cmd/main/main_test.go b/cmd/main/main_test.go new file mode 100644 index 0000000..a78823b --- /dev/null +++ b/cmd/main/main_test.go @@ -0,0 +1,119 @@ +package main + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gzzn.com/mini/ciimsproxy/internal" +) + +const ( + testErrMsg = `Can not find the event [FLOP-ESTT-ATC-ALL1]` + testSendOK = `` + testReceiveResp = `<?xml version="1.0" encoding="UTF-8"?><MSG><A>1</A></MSG>` +) + +func testRouter(t *testing.T, handler http.HandlerFunc) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + ciims := httptest.NewServer(handler) + t.Cleanup(ciims.Close) + client, err := internal.NewClient(10) + require.NoError(t, err) + return newRouter(Config{ServerURL: ciims.URL, Listen: ":0", Timeout: 10, Client: client}) +} + +func performJSON(r http.Handler, method, path, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +func TestPing(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) {}) + w := performJSON(r, http.MethodGet, "/ping", "") + assert.Equal(t, http.StatusOK, w.Code) + assert.JSONEq(t, `{"message":"pong"}`, w.Body.String()) +} + +func TestSendSuccess(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, testSendOK) + }) + w := performJSON(r, http.MethodPost, "/send", `{"user":"FIMS","pass":"x","event":"E1","msg":""}`) + assert.Equal(t, http.StatusOK, w.Code) + assert.JSONEq(t, `{"error":""}`, w.Body.String()) +} + +func TestSendSOAPFault(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, testErrMsg) + }) + w := performJSON(r, http.MethodPost, "/send", `{"user":"FIMS","pass":"x","event":"E1","msg":""}`) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, w.Body.String(), "Can not find the event") +} + +func TestSendMissingRequiredField(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) {}) + w := performJSON(r, http.MethodPost, "/send", `{"user":"FIMS","pass":"x","msg":""}`) + assert.Equal(t, http.StatusBadRequest, w.Code) +} + +func TestSendOversizedBody(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) {}) + body := `{"user":"FIMS","pass":"x","event":"E1","msg":"` + strings.Repeat("a", maxMsgLen) + `"}` + req := httptest.NewRequest(http.MethodPost, "/send", bytes.NewBufferString(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + assert.Equal(t, http.StatusRequestEntityTooLarge, w.Code) +} + +func TestReceiveSuccess(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, testReceiveResp) + }) + w := performJSON(r, http.MethodPost, "/receive", `{"user":"FIMS","pass":"x","count":2}`) + assert.Equal(t, http.StatusOK, w.Code) + assert.Contains(t, w.Body.String(), "MSG") +} + +func TestReceiveInvalidCount(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) {}) + + w := performJSON(r, http.MethodPost, "/receive", `{"user":"FIMS","pass":"x","count":0}`) + assert.Equal(t, http.StatusBadRequest, w.Code) + + w = performJSON(r, http.MethodPost, "/receive", `{"user":"FIMS","pass":"x","count":1001}`) + assert.Equal(t, http.StatusBadRequest, w.Code) +} + +func TestReceiveSOAPFault(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, testErrMsg) + }) + w := performJSON(r, http.MethodPost, "/receive", `{"user":"FIMS","pass":"x","count":2}`) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, w.Body.String(), "Can not find the event") +} + +func TestHTTP500WithSOAPFaultReturnsFaultText(t *testing.T) { + r := testRouter(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, testErrMsg) + }) + w := performJSON(r, http.MethodPost, "/send", `{"user":"FIMS","pass":"x","event":"E1","msg":""}`) + assert.Equal(t, http.StatusInternalServerError, w.Code) + assert.Contains(t, w.Body.String(), "Can not find the event") + assert.NotContains(t, w.Body.String(), "ciims returned 500") +} diff --git a/go.mod b/go.mod index 0f7244c..e3d6ce9 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,40 @@ module gzzn.com/mini/ciimsproxy -go 1.13 +go 1.22 require ( - github.com/gin-gonic/gin v1.6.3 - github.com/labstack/gommon v0.3.0 - github.com/stretchr/testify v1.5.1 + github.com/gin-gonic/gin v1.9.1 + github.com/stretchr/testify v1.8.4 +) + +require ( + github.com/bytedance/sonic v1.9.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.14.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.11 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + golang.org/x/arch v0.3.0 // indirect + golang.org/x/crypto v0.9.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.15.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 0312153..a61e7e5 100644 --- a/go.sum +++ b/go.sum @@ -1,60 +1,95 @@ +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= +github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= -github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= -github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= -github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= +github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= -github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= -github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= +github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasttemplate v1.0.1 h1:tY9CJiPnMXf1ERmG2EyK7gNUd+c6RKGD0IfU8WdUSz8= -github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= +golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= +golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/internal/codec.go b/internal/codec.go index b29071a..2f1e1c3 100644 --- a/internal/codec.go +++ b/internal/codec.go @@ -3,7 +3,7 @@ package internal import ( "bytes" "encoding/xml" - "regexp" + "io" "strconv" "strings" ) @@ -82,66 +82,71 @@ const ( ` - - msgExp = `.*<\/ns1:string>` - errExp = `` ) // CreateSend xml string for sending func CreateSend(user string, pass string, priority int, event string, valXML bool, message string) string { var mb bytes.Buffer xml.Escape(&mb, []byte(message)) - msg := strings.Replace(sendtpl, "##user##", user, -1) - msg = strings.Replace(msg, "##pass##", pass, -1) - msg = strings.Replace(msg, "##event##", event, -1) + msg := strings.Replace(sendtpl, "##user##", xmlEscape(user), -1) + msg = strings.Replace(msg, "##pass##", xmlEscape(pass), -1) + msg = strings.Replace(msg, "##event##", xmlEscape(event), -1) msg = strings.Replace(msg, "##priority##", strconv.Itoa(priority), -1) msg = strings.Replace(msg, "##xml##", strconv.FormatBool(valXML), -1) msg = strings.Replace(msg, "##msg##", mb.String(), -1) return msg } -//CreateReceive message +// CreateReceive message func CreateReceive(user string, pass string, count int) string { - msg := strings.Replace(receivetpl, "##user##", user, -1) - msg = strings.Replace(msg, "##pass##", pass, -1) + msg := strings.Replace(receivetpl, "##user##", xmlEscape(user), -1) + msg = strings.Replace(msg, "##pass##", xmlEscape(pass), -1) msg = strings.Replace(msg, "##count##", strconv.Itoa(count), -1) return msg } -//Map get values -func Map(vs []string, f func(string) string) []string { - vsm := make([]string, len(vs)) - for i, v := range vs { - vsm[i] = f(v) - } - return vsm +func xmlEscape(s string) string { + var buf bytes.Buffer + xml.Escape(&buf, []byte(s)) + return buf.String() } -//GetMsgs get message from soap response +// GetMsgs get message from soap response func GetMsgs(soap string) []string { - r, _ := regexp.Compile(msgExp) - msgs := r.FindAllString(soap, -1) - return Map(msgs, split) + return xmlElementTexts(soap, "string") } -//GetErrMsg get error message +// GetErrMsg get error message func GetErrMsg(soap string) string { - r, _ := regexp.Compile(errExp) - msg := r.FindAllString(soap, -1) - if len(msg) < 1 { - return "" + matches := xmlElementTexts(soap, "errorMessage") + if len(matches) > 0 { + return matches[0] } - if len(msg[0]) > 40 { - size := len(msg[0]) - return msg[0][54 : size-15] - } - return msg[0] + return "" } -func split(msg string) string { - if len(msg) > 12 { - return msg[12 : len(msg)-13] - } - return msg +func xmlElementTexts(soap string, localName string) []string { + decoder := xml.NewDecoder(strings.NewReader(soap)) + var result []string + for { + token, err := decoder.Token() + if err == io.EOF { + break + } + if err != nil { + return result + } + start, ok := token.(xml.StartElement) + if !ok || start.Name.Local != localName { + continue + } + + var text string + if err := decoder.DecodeElement(&text, &start); err != nil { + return result + } + result = append(result, text) + } + return result } diff --git a/internal/handler_test.go b/internal/handler_test.go new file mode 100644 index 0000000..8185cce --- /dev/null +++ b/internal/handler_test.go @@ -0,0 +1,174 @@ +package internal + +import ( + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClientSend_SOAPFault(t *testing.T) { + ciims := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/xml; charset=UTF-8") + fmt.Fprint(w, ErrMsg) + })) + defer ciims.Close() + + client, err := NewClient(10) + require.NoError(t, err) + resp, err := client.Send(ciims.URL+"/services/ExchangeService", "") + assert.NoError(t, err) + require.NotNil(t, resp) + + assert.True(t, resp.IsFault()) + assert.Equal(t, "Can not find the event [FLOP-ESTT-ATC-ALL1]", resp.ErrorMessage()) +} + +func TestClientSend_Success(t *testing.T) { + ciims := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/xml; charset=UTF-8") + fmt.Fprint(w, SendOk) + })) + defer ciims.Close() + + client, err := NewClient(10) + require.NoError(t, err) + resp, err := client.Send(ciims.URL+"/services/ExchangeService", "") + assert.NoError(t, err) + require.NotNil(t, resp) + + assert.Equal(t, "", resp.ErrorMessage()) +} + +func TestClientSend_ReceiveMessages(t *testing.T) { + ciims := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/xml; charset=UTF-8") + fmt.Fprint(w, ReceiveResp) + })) + defer ciims.Close() + + client, err := NewClient(10) + require.NoError(t, err) + resp, err := client.Send(ciims.URL+"/services/ExchangeService", "") + assert.NoError(t, err) + require.NotNil(t, resp) + + msgs := resp.Messages() + assert.Equal(t, 2, len(msgs)) + assert.Equal(t, Msg, msgs[0]) + assert.Equal(t, Msg, msgs[1]) +} + +func TestClientSend_NetworkTimeout(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + addr := listener.Addr().String() + + go func() { + conn, _ := listener.Accept() + if conn != nil { + io.Copy(io.Discard, conn) + conn.Close() + } + }() + + client, err := NewClient(1) + require.NoError(t, err) + _, err = client.Send("http://"+addr+"/services/ExchangeService", "") + listener.Close() + assert.Error(t, err) +} + +func TestClientSend_ServerError(t *testing.T) { + client, err := NewClient(1) + require.NoError(t, err) + _, err = client.Send("http://127.0.0.1:1/nonexistent", "") + assert.Error(t, err) +} + +func TestClientSend_HTTPStatusError(t *testing.T) { + ciims := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "backend failed", http.StatusInternalServerError) + })) + defer ciims.Close() + + client, err := NewClient(10) + require.NoError(t, err) + resp, err := client.Send(ciims.URL+"/services/ExchangeService", "") + require.Error(t, err) + require.NotNil(t, resp) + + var statusErr *HTTPStatusError + require.True(t, errors.As(err, &statusErr)) + assert.Equal(t, http.StatusInternalServerError, statusErr.StatusCode) + assert.Contains(t, statusErr.Body, "backend failed") +} + +func TestGetMsgs_Empty(t *testing.T) { + msgs := GetMsgs("") + assert.Equal(t, 0, len(msgs)) +} + +func TestGetMsgs_DifferentNamespacePrefix(t *testing.T) { + resp := ` + <MSG/> + ` + msgs := GetMsgs(resp) + assert.Equal(t, 1, len(msgs)) + assert.Equal(t, "", msgs[0]) +} + +func TestGetMsgs_AttributesWhitespaceAndMultiline(t *testing.T) { + resp := ` + + <MSG> + <A>1</A> + </MSG> + + ` + msgs := GetMsgs(resp) + require.Len(t, msgs, 1) + assert.Contains(t, msgs[0], "") + assert.Contains(t, msgs[0], "1") +} + +func TestGetErrMsg_NoError(t *testing.T) { + errMsg := GetErrMsg(SendOk) + assert.Equal(t, "", errMsg) +} + +func TestGetErrMsg_Empty(t *testing.T) { + errMsg := GetErrMsg("") + assert.Equal(t, "", errMsg) +} + +func TestGetErrMsg_AttributesWhitespaceAndMultiline(t *testing.T) { + resp := ` + + Can not find + the event + + ` + errMsg := GetErrMsg(resp) + assert.Contains(t, errMsg, "Can not find") + assert.Contains(t, errMsg, "the event") +} + +func TestCreateSend_XMLEscapes(t *testing.T) { + result := CreateSend("user<>&\"'", "pass", 0, "event", false, "") + assert.Contains(t, result, "user<>&"'") + assert.Contains(t, result, "pass") + assert.Contains(t, result, "<MSG/>") +} + +func TestCreateReceive_XMLEscapes(t *testing.T) { + result := CreateReceive("user<>&\"'", "pass>", 2) + assert.Contains(t, result, "user<>&"'") + assert.Contains(t, result, "pass>") +} diff --git a/internal/http.go b/internal/http.go index a6a0478..e2baa4f 100644 --- a/internal/http.go +++ b/internal/http.go @@ -1,8 +1,8 @@ package internal import ( - "bytes" - "io/ioutil" + "fmt" + "io" "net/http" "strings" "time" @@ -13,37 +13,85 @@ const ( defaultAgent string = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; XFire Client +http://xfire.codehaus.org)" ) -//Post xml string to url -func post(url string, contentType string, msg string) (*http.Response, error) { - return http.Post(url, contentType, bytes.NewBuffer([]byte(msg))) +type Client struct { + httpClient *http.Client } -func postSim(url string, msg string) (string, error) { - timeout := time.Duration(10 * time.Second) - client := http.Client{ - Timeout: timeout, - } +type CIIMSResponse struct { + RawXML string +} +type HTTPStatusError struct { + StatusCode int + Status string + Body string +} + +func (e *HTTPStatusError) Error() string { + body := e.Body + if len(body) > 512 { + body = body[:512] + "..." + } + if body == "" { + return fmt.Sprintf("ciims returned %s", e.Status) + } + return fmt.Sprintf("ciims returned %s: %s", e.Status, body) +} + +func NewClient(timeoutSec int) (*Client, error) { + if timeoutSec <= 0 { + return nil, fmt.Errorf("timeout must be positive") + } + return &Client{ + httpClient: &http.Client{ + Timeout: time.Duration(timeoutSec) * time.Second, + }, + }, nil +} + +func (r *CIIMSResponse) IsFault() bool { + return r != nil && r.ErrorMessage() != "" +} + +func (r *CIIMSResponse) ErrorMessage() string { + if r == nil { + return "" + } + return GetErrMsg(r.RawXML) +} + +func (r *CIIMSResponse) Messages() []string { + if r == nil { + return nil + } + return GetMsgs(r.RawXML) +} + +func (c *Client) Send(url string, msg string) (*CIIMSResponse, error) { req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(msg)) if err != nil { - return err.Error(), err + return nil, err } req.Header.Set("Content-Type", defaultContentType) req.Header.Set("User-Agent", defaultAgent) req.Header.Set("SOAPAction", "") - resp, err := client.Do(req) + resp, err := c.httpClient.Do(req) if err != nil { - return err.Error(), err + return nil, err } defer resp.Body.Close() - respBytes, err := ioutil.ReadAll(resp.Body) + respBytes, err := io.ReadAll(resp.Body) if err != nil { - return err.Error(), err + return nil, err } - return string(respBytes), nil -} - -//Send message -func Send(url string, message string) (string, error) { - return postSim(url, message) + body := string(respBytes) + ciimsResp := &CIIMSResponse{RawXML: body} + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + return ciimsResp, &HTTPStatusError{ + StatusCode: resp.StatusCode, + Status: resp.Status, + Body: body, + } + } + return ciimsResp, nil }