Thanks, I couldn’t find a simple example like that in the docs!
Now I have this code:
package dgraph
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"strings"
"time"
dgo "github.com/dgraph-io/dgo/v210"
"github.com/dgraph-io/dgo/v210/protos/api"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)
type authorizationCredentials struct {
token string
}
func (a *authorizationCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{"Authorization": fmt.Sprintf("Bearer %s", a.token)}, nil
}
func (a *authorizationCredentials) RequireTransportSecurity() bool {
return true
}
func (dg *Dgraph) Connect() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
pool, err := x509.SystemCertPool()
if err != nil {
log.Printf("error getting system certificate store - %s", err)
return err
}
// conn, err := dgo.DialCloud(dg.url, dg.token)
conn, err := grpc.Dial(dg.url, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: strings.Split(dg.url, ":")[0]})), grpc.WithPerRPCCredentials(&authorizationCredentials{dg.token}))
if err != nil {
log.Printf("error connecting to Dgraph cloud - %s", err)
return err
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
dg.client = dgraphClient
// err = dgraphClient.Login(context.Background(), "user", "passwd")
// if err != nil {
// log.Printf("error logging in: %s", err)
// return err
// }
md := metadata.New(map[string]string{"accept": "application/dql", "content-type": "application/dql"})
ctx = metadata.NewOutgoingContext(ctx, md)
txn := dg.client.NewTxn()
q := `{
q(func: type(Order)) {
uid
name
purchased
description
state
}
}`
res, err := txn.Query(ctx, q)
if err != nil {
log.Printf("error in query - %s", err)
return err
}
defer txn.Discard(ctx)
log.Printf("ORDERS: %s", string(res.Json))
return nil
}
which still gives this error:
2021/06/18 18:48:32 error in query - rpc error: code = Unauthenticated desc = Unauthorized: HTTP status code 401; transport: missing content-type field
2021/06/18 18:48:32 rpc error: code = Unauthenticated desc = Unauthorized: HTTP status code 401; transport: missing content-type field
exit status 1
make: *** [Makefile:22: grpc] Error 1