|
| 1 | +package middlewares |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "strconv" |
| 9 | + |
| 10 | + log "github.com/codeshelldev/secured-signal-api/utils/logger" |
| 11 | +) |
| 12 | + |
| 13 | +type MessageAlias struct { |
| 14 | + Alias string |
| 15 | + Priority int |
| 16 | +} |
| 17 | + |
| 18 | +type BodyMiddleware struct { |
| 19 | + Next http.Handler |
| 20 | + MessageAliases []MessageAlias |
| 21 | +} |
| 22 | + |
| 23 | +func (data BodyMiddleware) Use() http.Handler { |
| 24 | + next := data.Next |
| 25 | + messageAliases := data.MessageAliases |
| 26 | + |
| 27 | + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 28 | + bodyBytes, err := io.ReadAll(req.Body) |
| 29 | + if err != nil { |
| 30 | + log.Error("Could not read Body: ", err.Error()) |
| 31 | + http.Error(w, "Bad Request", http.StatusBadRequest) |
| 32 | + return |
| 33 | + } |
| 34 | + defer req.Body.Close() |
| 35 | + |
| 36 | + if len(bodyBytes) > 0 { |
| 37 | + |
| 38 | + req.Body.Close() |
| 39 | + |
| 40 | + var modifiedBodyData map[string]interface{} |
| 41 | + |
| 42 | + err = json.Unmarshal(bodyBytes, &modifiedBodyData) |
| 43 | + |
| 44 | + if err != nil { |
| 45 | + log.Error("Could not decode Body: ", err.Error()) |
| 46 | + http.Error(w, "Internal Error", http.StatusInternalServerError) |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + content, ok := modifiedBodyData["message"] |
| 51 | + |
| 52 | + if !ok || content == "" { |
| 53 | + best := 0 |
| 54 | + |
| 55 | + for _, alias := range messageAliases { |
| 56 | + aliasKey := alias.Alias |
| 57 | + priority := alias.Priority |
| 58 | + |
| 59 | + value, ok := modifiedBodyData[aliasKey] |
| 60 | + |
| 61 | + if ok && value != "" && priority > best { |
| 62 | + content = modifiedBodyData[aliasKey] |
| 63 | + } |
| 64 | + |
| 65 | + modifiedBodyData[aliasKey] = nil |
| 66 | + } |
| 67 | + |
| 68 | + modifiedBodyData["message"] = content |
| 69 | + |
| 70 | + bodyBytes, err = json.Marshal(modifiedBodyData) |
| 71 | + |
| 72 | + if err != nil { |
| 73 | + log.Error("Could not encode Body: ", err.Error()) |
| 74 | + http.Error(w, "Internal Error", http.StatusInternalServerError) |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + modifiedBody := string(bodyBytes) |
| 79 | + |
| 80 | + req.ContentLength = int64(len(modifiedBody)) |
| 81 | + req.Header.Set("Content-Length", strconv.Itoa(len(modifiedBody))) |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + req.Body = io.NopCloser(bytes.NewReader(bodyBytes)) |
| 86 | + |
| 87 | + next.ServeHTTP(w, req) |
| 88 | + }) |
| 89 | +} |
0 commit comments