Skip to content

Commit

Permalink
Adding http handler for lookup subjects stream response
Browse files Browse the repository at this point in the history
  • Loading branch information
akoserwal committed Jun 12, 2024
1 parent 3ec86bf commit 350adc9
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import (
v0 "ciam-rebac/api/relations/v0"
"ciam-rebac/internal/conf"
"ciam-rebac/internal/service"
"context"
"encoding/json"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"io"
nethttp "net/http"

"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/middleware/recovery"
Expand Down Expand Up @@ -35,5 +41,51 @@ func NewHTTPServer(c *conf.Server, relationships *service.RelationshipsService,
v0.RegisterKesselTupleServiceHTTPServer(srv, relationships)
v0.RegisterKesselCheckServiceHTTPServer(srv, check)
h.RegisterKesselHealthHTTPServer(srv, health)

srv.HandleFunc("/v0/subjects", func(writer nethttp.ResponseWriter, request *nethttp.Request) {
conn, err := grpc.NewClient(c.Grpc.Addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("could not connect to grpc server: %v", err)
}
defer conn.Close()

lookupServiceClient := v0.NewKesselLookupServiceClient(conn)

body, err := io.ReadAll(request.Body)
if err != nil {
nethttp.Error(writer, "Failed to read lookup subject body: "+err.Error(), nethttp.StatusInternalServerError)
return
}

lookupSubjectsRequest := v0.LookupSubjectsRequest{}
if err := json.Unmarshal(body, &lookupSubjectsRequest); err != nil {
nethttp.Error(writer, "Failed to unmarshal lookup request body: "+err.Error(), nethttp.StatusBadRequest)
return
}
stream, err := lookupServiceClient.LookupSubjects(context.Background(), &lookupSubjectsRequest)
if err != nil {
nethttp.Error(writer, "error grpc stream", nethttp.StatusInternalServerError)
return
}
var responses []*v0.LookupSubjectsResponse
for {
response, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
nethttp.Error(writer, "Failed to receive data from lookup subject stream: "+err.Error(), nethttp.StatusInternalServerError)
return
}
writer.Header().Set("Content-Type", "application/json")
writer.Header().Set("Transfer-Encoding", "chunked")

responses = append(responses, response)
}
if err := json.NewEncoder(writer).Encode(responses); err != nil {
nethttp.Error(writer, "Failed to encode lookup subject response: "+err.Error(), nethttp.StatusInternalServerError)
return
}
})
return srv
}

0 comments on commit 350adc9

Please sign in to comment.