Skip to content

Commit

Permalink
feat: add callback remove funcion
Browse files Browse the repository at this point in the history
  • Loading branch information
SevereCloud committed Jun 1, 2021
1 parent a41fd2d commit fd53737
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
16 changes: 14 additions & 2 deletions callback/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ func (cb *Callback) HandleFunc(w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, internal.CallbackRetryCounterKey, retryCounter)

var (
code int
date time.Time
code int
date time.Time
remove bool
)

retryAfter := func(c int, d time.Time) {
Expand All @@ -93,13 +94,24 @@ func (cb *Callback) HandleFunc(w http.ResponseWriter, r *http.Request) {
}
ctx = context.WithValue(ctx, internal.CallbackRetryAfterKey, retryAfter)

removeFunc := func() {
remove = true
}
ctx = context.WithValue(ctx, internal.CallbackRemove, removeFunc)

if err := cb.Handler(ctx, e); err != nil {
cb.logf("callback: %v", err)
http.Error(w, "Bad Request", http.StatusBadRequest)

return
}

if remove {
_, _ = w.Write([]byte("remove"))

return
}

if code != 0 {
w.Header().Set("Retry-After", date.Format(http.TimeFormat)) // RFC 7231, 7.1.3
http.Error(w, http.StatusText(code), code)
Expand Down
5 changes: 5 additions & 0 deletions callback/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,8 @@ func RetryAfter(ctx context.Context, code int, date time.Time) {
date,
)
}

// Remove VK Callback server.
func Remove(ctx context.Context) {
ctx.Value(internal.CallbackRemove).(func())()
}
23 changes: 23 additions & 0 deletions callback/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,26 @@ func TestRetryAfter(t *testing.T) {
assert.Equal(t, code, rr.Code)
assert.Equal(t, date.Format(http.TimeFormat), rr.Header().Get("Retry-After"))
}

func TestRemove(t *testing.T) {
t.Parallel()

cb := callback.NewCallback()
cb.MessageNew(func(ctx context.Context, obj events.MessageNewObject) {
callback.Remove(ctx)
})

jsonStr := []byte(`{"type": "message_new","object": {}}`)

req, err := http.NewRequest("POST", "/callback", bytes.NewBuffer(jsonStr))
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
handler := http.HandlerFunc(cb.HandleFunc)

handler.ServeHTTP(rr, req)

assert.Equal(t, "remove", rr.Body.String())
}
1 change: 1 addition & 0 deletions internal/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const (
LongPollTsKey
CallbackRetryCounterKey
CallbackRetryAfterKey
CallbackRemove
)

// ContextClient return *http.Client.
Expand Down

0 comments on commit fd53737

Please sign in to comment.