github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/ext/tlhttp/http.go (about)

     1  package tlhttp
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/nikandfor/tlog"
     7  )
     8  
     9  var TraceIDKey = "Traceid"
    10  
    11  func SpawnOrStart(w http.ResponseWriter, req *http.Request, kvs ...interface{}) tlog.Span {
    12  	return spawnOrStart(tlog.DefaultLogger, w, req, kvs)
    13  }
    14  
    15  func SpawnOrStartLogger(l *tlog.Logger, w http.ResponseWriter, req *http.Request, kvs ...interface{}) tlog.Span {
    16  	return spawnOrStart(l, w, req, kvs)
    17  }
    18  
    19  func spawnOrStart(l *tlog.Logger, w http.ResponseWriter, req *http.Request, kvs []interface{}) tlog.Span {
    20  	var trid tlog.ID
    21  	var err error
    22  
    23  	xtr := req.Header.Get(TraceIDKey)
    24  	if xtr != "" {
    25  		trid, err = tlog.IDFromString(xtr)
    26  	}
    27  
    28  	tr := l.NewSpan(2, trid, "http_request", append([]interface{}{
    29  		"client", req.RemoteAddr,
    30  		"method", req.Method,
    31  		"path", req.URL.Path,
    32  	}, kvs...)...)
    33  
    34  	if err != nil {
    35  		tr.Printw("bad parent trace id", "id", xtr, "err", err)
    36  	}
    37  
    38  	w.Header().Set(TraceIDKey, tr.ID.StringFull())
    39  
    40  	return tr
    41  }