github.com/v2fly/tools@v0.100.0/internal/lsp/protocol/context.go (about)

     1  // Copyright 2019 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package protocol
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  
    11  	"github.com/v2fly/tools/internal/event"
    12  	"github.com/v2fly/tools/internal/event/core"
    13  	"github.com/v2fly/tools/internal/event/export"
    14  	"github.com/v2fly/tools/internal/event/label"
    15  	"github.com/v2fly/tools/internal/xcontext"
    16  )
    17  
    18  type contextKey int
    19  
    20  const (
    21  	clientKey = contextKey(iota)
    22  )
    23  
    24  func WithClient(ctx context.Context, client Client) context.Context {
    25  	return context.WithValue(ctx, clientKey, client)
    26  }
    27  
    28  func LogEvent(ctx context.Context, ev core.Event, lm label.Map, mt MessageType) context.Context {
    29  	client, ok := ctx.Value(clientKey).(Client)
    30  	if !ok {
    31  		return ctx
    32  	}
    33  	buf := &bytes.Buffer{}
    34  	p := export.Printer{}
    35  	p.WriteEvent(buf, ev, lm)
    36  	msg := &LogMessageParams{Type: mt, Message: buf.String()}
    37  	// Handle messages generated via event.Error, which won't have a level Label.
    38  	if event.IsError(ev) {
    39  		msg.Type = Error
    40  	}
    41  	go client.LogMessage(xcontext.Detach(ctx), msg)
    42  	return ctx
    43  }