Skip to content

Commit

Permalink
propagation context from request to store
Browse files Browse the repository at this point in the history
  • Loading branch information
neftales committed Jun 8, 2024
1 parent 59801b1 commit ce5c782
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
6 changes: 6 additions & 0 deletions context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package context

import (
"context"
"fmt"
"net/http"
)

Expand All @@ -11,5 +12,10 @@ type Store interface {

func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data, err := store.Fetch(r.Context())
if err != nil {
return
}
fmt.Fprint(w, data)
}
}
25 changes: 24 additions & 1 deletion context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package context

import (
"context"
"errors"
"log"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -40,6 +41,24 @@ func (s *SpyStore) Fetch(ctx context.Context) (string, error) {
}
}

type SpyResponseWriter struct {
written bool
}

func (s *SpyResponseWriter) Header() http.Header {
s.written = true
return nil
}

func (s *SpyResponseWriter) Write([]byte) (int, error) {
s.written = true
return 0, errors.New("not implemented")
}

func (s *SpyResponseWriter) WriteHeader(statusCode int) {
s.written = true
}

func TestServer(t *testing.T) {
t.Run("returns data from store", func(t *testing.T) {
data := "hello, world"
Expand Down Expand Up @@ -67,8 +86,12 @@ func TestServer(t *testing.T) {
time.AfterFunc(5*time.Millisecond, cancel)
request = request.WithContext(cancellingCtx)

response := httptest.NewRecorder()
response := &SpyResponseWriter{}

svr.ServeHTTP(response, request)

if response.written {
t.Error("a response should not have been written")
}
})
}

0 comments on commit ce5c782

Please sign in to comment.