Skip to content

Commit

Permalink
Using jsoniter to encode promql responses
Browse files Browse the repository at this point in the history
Signed-off-by: alanprot <alanprot@gmail.com>
  • Loading branch information
alanprot committed Jun 5, 2024
1 parent f4ca9bc commit bc1338a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
7 changes: 6 additions & 1 deletion pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
package api

import (
"encoding/json"
"fmt"
"net/http"
"os"
Expand All @@ -29,6 +28,7 @@ import (

"github.com/go-kit/log"
"github.com/go-kit/log/level"
jsoniter "github.com/json-iterator/go"
"github.com/klauspost/compress/gzhttp"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/common/route"
Expand Down Expand Up @@ -66,6 +66,11 @@ var corsHeaders = map[string]string{
"Access-Control-Expose-Headers": "Date",
}

var (
// Let suse the same json codec used by upstream prometheus.
json = jsoniter.ConfigCompatibleWithStandardLibrary
)

// ThanosVersion contains build information about Thanos.
type ThanosVersion struct {
Version string `json:"version"`
Expand Down
37 changes: 36 additions & 1 deletion pkg/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package api

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
Expand All @@ -28,12 +27,48 @@ import (
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/common/route"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/promql/parser"
promApiV1 "github.com/prometheus/prometheus/web/api/v1"

"github.com/efficientgo/core/testutil"
extpromhttp "github.com/thanos-io/thanos/pkg/extprom/http"
"github.com/thanos-io/thanos/pkg/logging"
)

func TestMarshallMatrixNull(t *testing.T) {
var m promql.Matrix
result := response{
Status: StatusSuccess,
Data: promApiV1.QueryData{
ResultType: parser.ValueTypeMatrix,
Result: m, // null
},
}

b1, err := json.Marshal(result)
if err != nil {
t.Fatalf("Error marshaling response body: %s", err)
}

exp := response{
Status: StatusSuccess,
Data: promApiV1.QueryData{
ResultType: parser.ValueTypeMatrix,
Result: promql.Matrix{},
},
}

b2, err := json.Marshal(exp)
if err != nil {
t.Fatalf("Error marshaling response body: %s", err)
}

if !reflect.DeepEqual(b1, b2) {
t.Fatalf("Expected response \n%v\n but got \n%v\n", string(b1), string(b2))
}
}

func TestRespondSuccess(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Respond(w, "test", nil)
Expand Down

0 comments on commit bc1338a

Please sign in to comment.