Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test for reading trace from http request header #88

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions logtracing/span.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ func (s *span) AppendKVs(keyvals ...interface{}) {
s.keyvals = append(s.keyvals, keyvals...)
}

func (s *span) TraceID() string {
return s.traceID.String()
}

func (s *span) meta() spanMeta {
return spanMeta{
TraceID: s.traceID,
Expand Down
29 changes: 29 additions & 0 deletions server/logger_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package server

import (
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/theplant/appkit/contexts"
"github.com/theplant/appkit/log"
"github.com/theplant/appkit/logtracing"
)

func TestLogRequest(t *testing.T) {
Expand All @@ -32,4 +36,29 @@ func TestLogRequest(t *testing.T) {
if rw.Result().StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d", rw.Result().StatusCode)
}

r16 := make([]byte, 16)
r8 := make([]byte, 8)
rand.Read(r16)
rand.Read(r8)
traceID := hex.EncodeToString(r16)
spanID := hex.EncodeToString(r8)
trace := fmt.Sprintf("%s-%s-%s-%s", "00", traceID, spanID, "00")
req, err = http.NewRequest("GET", "http://example.com", nil)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
req.Header.Add(traceHeaderKey, trace)
h = Compose(
// Recovery should come before logReq to set the status code to 500
Recovery,
LogRequest,
)(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
_, span := logtracing.StartSpan(r.Context(), "")
if span.TraceID() != traceID {
t.Errorf("traceID should be: %s, but got: %s", traceID, span.TraceID())
}
}))

h.ServeHTTP(rw, req)
}