Skip to content

Commit ec68e7e

Browse files
authored
Improve some more code (#107)
* Improve some more code - Error handling of json responses - Removed old pattern of FromJSON/ToJson functions. - Return structs, accept interfaces. - Added the config file to .gitignore for easier development. - Added a sample config
1 parent 351d6b3 commit ec68e7e

10 files changed

+73
-113
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ node_modules
5757
# Swagger output file
5858
index.html
5959

60+
config/mattermost-push-proxy.json
6061
# Ignore config.json
6162
cmd/renew_apple_cert/convert_cert/config/**
6263
cmd/renew_apple_cert/convert_cert/config.json

config/mattermost-push-proxy.json renamed to config/mattermost-push-proxy.sample.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
"AppleTeamID": ""
2727
}
2828
],
29-
"AndroidPushSettings":[
29+
"AndroidPushSettings": [
3030
{
3131
"Type":"android",
3232
"AndroidApiKey":""

server/android_notification_server.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ type AndroidNotificationServer struct {
1616
AndroidPushSettings AndroidPushSettings
1717
}
1818

19-
func NewAndroidNotificationServer(settings AndroidPushSettings, logger *Logger, metrics *metrics) NotificationServer {
19+
func NewAndroidNotificationServer(settings AndroidPushSettings, logger *Logger, metrics *metrics) *AndroidNotificationServer {
2020
return &AndroidNotificationServer{
2121
AndroidPushSettings: settings,
2222
metrics: metrics,
@@ -37,7 +37,7 @@ func (me *AndroidNotificationServer) Initialize() bool {
3737

3838
func (me *AndroidNotificationServer) SendNotification(msg *PushNotification) PushResponse {
3939
pushType := msg.Type
40-
data := map[string]interface{}{
40+
data := map[string]any{
4141
"ack_id": msg.AckID,
4242
"type": pushType,
4343
"version": msg.Version,

server/apple_notification_server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ type AppleNotificationServer struct {
2424
ApplePushSettings ApplePushSettings
2525
}
2626

27-
func NewAppleNotificationServer(settings ApplePushSettings, logger *Logger, metrics *metrics) NotificationServer {
27+
func NewAppleNotificationServer(settings ApplePushSettings, logger *Logger, metrics *metrics) *AppleNotificationServer {
2828
return &AppleNotificationServer{
2929
ApplePushSettings: settings,
3030
metrics: metrics,

server/metrics_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func TestMetricDisabled(t *testing.T) {
1616
platform := "junk"
1717
pushType := PushTypeMessage
1818

19-
fileName := FindConfigFile("mattermost-push-proxy.json")
19+
fileName := FindConfigFile("mattermost-push-proxy.sample.json")
2020
cfg, err := LoadConfig(fileName)
2121
require.NoError(t, err)
2222
cfg.AndroidPushSettings[0].AndroidAPIKey = platform
@@ -64,7 +64,7 @@ func TestMetricEnabled(t *testing.T) {
6464
platform := "junk"
6565
pushType := PushTypeMessage
6666

67-
fileName := FindConfigFile("mattermost-push-proxy.json")
67+
fileName := FindConfigFile("mattermost-push-proxy.sample.json")
6868
cfg, err := LoadConfig(fileName)
6969
require.NoError(t, err)
7070
cfg.AndroidPushSettings[0].AndroidAPIKey = platform

server/push_notification.go

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,6 @@
33

44
package server
55

6-
import (
7-
"encoding/json"
8-
"io"
9-
)
10-
116
const (
127
PushNotifyApple = "apple"
138
PushNotifyAndroid = "android"
@@ -56,40 +51,3 @@ type PushNotification struct {
5651
IsCRTEnabled bool `json:"is_crt_enabled"`
5752
IsIDLoaded bool `json:"is_id_loaded"`
5853
}
59-
60-
func (me *PushNotification) ToJson() string {
61-
b, err := json.Marshal(me)
62-
if err != nil {
63-
return ""
64-
}
65-
return string(b)
66-
}
67-
68-
func PushNotificationFromJson(data io.Reader) *PushNotification {
69-
decoder := json.NewDecoder(data)
70-
var me PushNotification
71-
err := decoder.Decode(&me)
72-
if err == nil {
73-
return &me
74-
} else {
75-
return nil
76-
}
77-
}
78-
79-
func (me *PushNotificationAck) ToJSON() string {
80-
b, err := json.Marshal(me)
81-
if err != nil {
82-
return ""
83-
}
84-
return string(b)
85-
}
86-
87-
func PushNotificationAckFromJSON(data io.Reader) *PushNotificationAck {
88-
var me PushNotificationAck
89-
decoder := json.NewDecoder(data)
90-
err := decoder.Decode(&me)
91-
if err == nil {
92-
return &me
93-
}
94-
return nil
95-
}

server/push_notification_test.go

Lines changed: 0 additions & 19 deletions
This file was deleted.

server/push_response.go

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,6 @@ func NewErrorPushResponse(message string) PushResponse {
3737
return m
3838
}
3939

40-
func (me *PushResponse) ToJson() string {
41-
if b, err := json.Marshal(me); err != nil {
42-
return ""
43-
} else {
44-
return string(b)
45-
}
46-
}
47-
4840
func PushResponseFromJson(data io.Reader) PushResponse {
4941
decoder := json.NewDecoder(data)
5042

server/server.go

Lines changed: 46 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package server
55

66
import (
77
"context"
8+
"encoding/json"
89
"fmt"
910
"net"
1011
"net/http"
@@ -154,13 +155,15 @@ func (s *Server) responseTimeMiddleware(f func(w http.ResponseWriter, r *http.Re
154155
}
155156

156157
func (s *Server) handleSendNotification(w http.ResponseWriter, r *http.Request) {
157-
msg := PushNotificationFromJson(r.Body)
158-
159-
if msg == nil {
160-
rMsg := "Failed to read message body"
158+
var msg PushNotification
159+
err := json.NewDecoder(r.Body).Decode(&msg)
160+
if err != nil {
161+
rMsg := fmt.Sprintf("Failed to read message body: %v", err)
161162
s.logger.Error(rMsg)
162163
resp := NewErrorPushResponse(rMsg)
163-
_, _ = w.Write([]byte(resp.ToJson()))
164+
if err2 := json.NewEncoder(w).Encode(resp); err2 != nil {
165+
s.logger.Errorf("Failed to write response: %v", err2)
166+
}
164167
if s.metrics != nil {
165168
s.metrics.incrementBadRequest()
166169
}
@@ -171,7 +174,9 @@ func (s *Server) handleSendNotification(w http.ResponseWriter, r *http.Request)
171174
rMsg := "Failed because of missing server Id"
172175
s.logger.Error(rMsg)
173176
resp := NewErrorPushResponse(rMsg)
174-
_, _ = w.Write([]byte(resp.ToJson()))
177+
if err2 := json.NewEncoder(w).Encode(resp); err2 != nil {
178+
s.logger.Errorf("Failed to write response: %v", err2)
179+
}
175180
if s.metrics != nil {
176181
s.metrics.incrementBadRequest()
177182
}
@@ -182,7 +187,9 @@ func (s *Server) handleSendNotification(w http.ResponseWriter, r *http.Request)
182187
rMsg := fmt.Sprintf("Failed because of missing device Id serverId=%v", msg.ServerID)
183188
s.logger.Error(rMsg)
184189
resp := NewErrorPushResponse(rMsg)
185-
_, _ = w.Write([]byte(resp.ToJson()))
190+
if err2 := json.NewEncoder(w).Encode(resp); err2 != nil {
191+
s.logger.Errorf("Failed to write response: %v", err2)
192+
}
186193
if s.metrics != nil {
187194
s.metrics.incrementBadRequest()
188195
}
@@ -210,29 +217,34 @@ func (s *Server) handleSendNotification(w http.ResponseWriter, r *http.Request)
210217
}
211218

212219
if server, ok := s.pushTargets[msg.Platform]; ok {
213-
rMsg := server.SendNotification(msg)
214-
_, _ = w.Write([]byte(rMsg.ToJson()))
215-
return
216-
} else {
217-
rMsg := fmt.Sprintf("Did not send message because of missing platform property type=%v serverId=%v", msg.Platform, msg.ServerID)
218-
s.logger.Error(rMsg)
219-
resp := NewErrorPushResponse(rMsg)
220-
_, _ = w.Write([]byte(resp.ToJson()))
221-
if s.metrics != nil {
222-
s.metrics.incrementBadRequest()
220+
rMsg := server.SendNotification(&msg)
221+
if err2 := json.NewEncoder(w).Encode(rMsg); err2 != nil {
222+
s.logger.Errorf("Failed to write message: %v", err2)
223223
}
224224
return
225225
}
226+
rMsg := fmt.Sprintf("Did not send message because of missing platform property type=%v serverId=%v", msg.Platform, msg.ServerID)
227+
s.logger.Error(rMsg)
228+
resp := NewErrorPushResponse(rMsg)
229+
err = json.NewEncoder(w).Encode(resp)
230+
if err != nil {
231+
s.logger.Errorf("Failed to write response: %v", err)
232+
}
233+
if s.metrics != nil {
234+
s.metrics.incrementBadRequest()
235+
}
226236
}
227237

228238
func (s *Server) handleAckNotification(w http.ResponseWriter, r *http.Request) {
229-
ack := PushNotificationAckFromJSON(r.Body)
230-
231-
if ack == nil {
232-
msg := "Failed to read ack body"
239+
var ack PushNotificationAck
240+
err := json.NewDecoder(r.Body).Decode(&ack)
241+
if err != nil {
242+
msg := fmt.Sprintf("Failed to read ack body: %v", err)
233243
s.logger.Error(msg)
234244
resp := NewErrorPushResponse(msg)
235-
_, _ = w.Write([]byte(resp.ToJson()))
245+
if err2 := json.NewEncoder(w).Encode(resp); err2 != nil {
246+
s.logger.Errorf("Failed to write response: %v", err2)
247+
}
236248
if s.metrics != nil {
237249
s.metrics.incrementBadRequest()
238250
}
@@ -243,7 +255,9 @@ func (s *Server) handleAckNotification(w http.ResponseWriter, r *http.Request) {
243255
msg := "Failed because of missing ack Id"
244256
s.logger.Error(msg)
245257
resp := NewErrorPushResponse(msg)
246-
_, _ = w.Write([]byte(resp.ToJson()))
258+
if err := json.NewEncoder(w).Encode(resp); err != nil {
259+
s.logger.Errorf("Failed to write response: %v", err)
260+
}
247261
if s.metrics != nil {
248262
s.metrics.incrementBadRequest()
249263
}
@@ -254,7 +268,9 @@ func (s *Server) handleAckNotification(w http.ResponseWriter, r *http.Request) {
254268
msg := "Failed because of missing ack platform"
255269
s.logger.Error(msg)
256270
resp := NewErrorPushResponse(msg)
257-
_, _ = w.Write([]byte(resp.ToJson()))
271+
if err := json.NewEncoder(w).Encode(resp); err != nil {
272+
s.logger.Errorf("Failed to write response: %v", err)
273+
}
258274
if s.metrics != nil {
259275
s.metrics.incrementBadRequest()
260276
}
@@ -265,7 +281,9 @@ func (s *Server) handleAckNotification(w http.ResponseWriter, r *http.Request) {
265281
msg := "Failed because of missing ack type"
266282
s.logger.Error(msg)
267283
resp := NewErrorPushResponse(msg)
268-
_, _ = w.Write([]byte(resp.ToJson()))
284+
if err := json.NewEncoder(w).Encode(resp); err != nil {
285+
s.logger.Errorf("Failed to write response: %v", err)
286+
}
269287
if s.metrics != nil {
270288
s.metrics.incrementBadRequest()
271289
}
@@ -279,7 +297,9 @@ func (s *Server) handleAckNotification(w http.ResponseWriter, r *http.Request) {
279297
}
280298

281299
rMsg := NewOkPushResponse()
282-
_, _ = w.Write([]byte(rMsg.ToJson()))
300+
if err := json.NewEncoder(w).Encode(rMsg); err != nil {
301+
s.logger.Errorf("Failed to write message: %v", err)
302+
}
283303
}
284304

285305
func (s *Server) getIpAddress(r *http.Request) string {

server/server_test.go

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,17 @@
44
package server
55

66
import (
7+
"bytes"
8+
"encoding/json"
79
"net/http"
8-
"strings"
910
"testing"
1011
"time"
1112

1213
"github.com/stretchr/testify/require"
1314
)
1415

1516
func TestBasicServer(t *testing.T) {
16-
fileName := FindConfigFile("mattermost-push-proxy.json")
17+
fileName := FindConfigFile("mattermost-push-proxy.sample.json")
1718
cfg, err := LoadConfig(fileName)
1819
require.NoError(t, err)
1920

@@ -30,9 +31,11 @@ func TestBasicServer(t *testing.T) {
3031

3132
// Test for missing server Id
3233
client := http.Client{}
33-
rq, _ := http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", strings.NewReader(msg.ToJson()))
34-
if resp, err := client.Do(rq); err != nil {
35-
t.Fatal(err)
34+
buf, err := json.Marshal(msg)
35+
require.NoError(t, err)
36+
rq, _ := http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", bytes.NewReader(buf))
37+
if resp, err2 := client.Do(rq); err2 != nil {
38+
t.Fatal(err2)
3639
} else {
3740
pr := PushResponseFromJson(resp.Body)
3841
if pr == nil || pr[PUSH_STATUS] != PUSH_STATUS_FAIL {
@@ -43,9 +46,11 @@ func TestBasicServer(t *testing.T) {
4346
// Test for missing platform type
4447
msg.ServerID = "test"
4548
client = http.Client{}
46-
rq, _ = http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", strings.NewReader(msg.ToJson()))
47-
if resp, err := client.Do(rq); err != nil {
48-
t.Fatal(err)
49+
buf, err = json.Marshal(msg)
50+
require.NoError(t, err)
51+
rq, _ = http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", bytes.NewReader(buf))
52+
if resp, err2 := client.Do(rq); err2 != nil {
53+
t.Fatal(err2)
4954
} else {
5055
pr := PushResponseFromJson(resp.Body)
5156
if pr == nil || pr[PUSH_STATUS] != PUSH_STATUS_FAIL {
@@ -55,12 +60,13 @@ func TestBasicServer(t *testing.T) {
5560

5661
// Test for junk platform type
5762
msg.Platform = "junk"
58-
rq, _ = http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", strings.NewReader(msg.ToJson()))
63+
buf, err = json.Marshal(msg)
64+
require.NoError(t, err)
65+
rq, _ = http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", bytes.NewReader(buf))
5966
if resp, err := client.Do(rq); err != nil {
6067
t.Fatal(err)
6168
} else {
6269
pr := PushResponseFromJson(resp.Body)
63-
println(pr.ToJson())
6470
if pr == nil || pr[PUSH_STATUS] != PUSH_STATUS_FAIL {
6571
t.Fatal("invalid response")
6672
}
@@ -71,7 +77,7 @@ func TestBasicServer(t *testing.T) {
7177
}
7278

7379
func TestAndroidSend(t *testing.T) {
74-
fileName := FindConfigFile("mattermost-push-proxy.json")
80+
fileName := FindConfigFile("mattermost-push-proxy.sample.json")
7581
cfg, err := LoadConfig(fileName)
7682
require.NoError(t, err)
7783

@@ -90,7 +96,9 @@ func TestAndroidSend(t *testing.T) {
9096
msg.DeviceID = "test"
9197

9298
client := http.Client{}
93-
rq, _ := http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", strings.NewReader(msg.ToJson()))
99+
buf, err := json.Marshal(msg)
100+
require.NoError(t, err)
101+
rq, _ := http.NewRequest("POST", "http://localhost:8066/api/v1/send_push", bytes.NewReader(buf))
94102
if resp, err := client.Do(rq); err != nil {
95103
t.Fatal(err)
96104
} else {

0 commit comments

Comments
 (0)