github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/util/marshal/legacy/marshal.go (about)

     1  // Package marshal converts internal objects to loghttp model objects.  This package is designed to work with
     2  //  models in pkg/loghttp/legacy.
     3  package marshal
     4  
     5  import (
     6  	"fmt"
     7  	"io"
     8  
     9  	"github.com/gorilla/websocket"
    10  	json "github.com/json-iterator/go"
    11  
    12  	loghttp "github.com/grafana/loki/pkg/loghttp/legacy"
    13  	"github.com/grafana/loki/pkg/logproto"
    14  	"github.com/grafana/loki/pkg/logqlmodel"
    15  )
    16  
    17  // Note that the below methods directly marshal the values passed in.  This is because these objects currently marshal
    18  // cleanly to the legacy http protocol (because that was how it was initially implemented).  If this ever changes,
    19  // it will be caught by testing and we will have to handle legacy like we do v1:  1) exchange a variety of structs for
    20  // for loghttp model objects 2) marshal the loghttp model objects
    21  
    22  // WriteQueryResponseJSON marshals promql.Value to legacy loghttp JSON and then writes it to the provided io.Writer
    23  func WriteQueryResponseJSON(v logqlmodel.Result, w io.Writer) error {
    24  	if v.Data.Type() != logqlmodel.ValueTypeStreams {
    25  		return fmt.Errorf("legacy endpoints only support %s result type, current type is %s", logqlmodel.ValueTypeStreams, v.Data.Type())
    26  	}
    27  
    28  	j := map[string]interface{}{
    29  		"streams": v.Data,
    30  		"stats":   v.Statistics,
    31  	}
    32  
    33  	return json.NewEncoder(w).Encode(j)
    34  }
    35  
    36  // WriteLabelResponseJSON marshals the logproto.LabelResponse to legacy loghttp JSON and then writes it to the provided writer
    37  func WriteLabelResponseJSON(l logproto.LabelResponse, w io.Writer) error {
    38  	return json.NewEncoder(w).Encode(l)
    39  }
    40  
    41  // WriteTailResponseJSON marshals the TailResponse to legacy loghttp JSON and then writes it to the provided connection
    42  func WriteTailResponseJSON(r loghttp.TailResponse, c *websocket.Conn) error {
    43  	return c.WriteJSON(r)
    44  }