# Example of using go client to connect to Dgraph

**URL:** <https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213>\
**Category:** Dgraph\
**Tags:** example\
**Created:** [June 15, 2020, 5:30pm UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213 "2020-06-15T17:30:50Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![trdeepak](https://yyz1.discourse-cdn.com/flex007/user_avatar/discuss.dgraph.io/trdeepak/32/3523_2.png) [@trdeepak](https://discuss.dgraph.io/u/trdeepak)\
**Post date:** [June 15, 2020, 5:30pm UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213/1 "2020-06-15T17:30:50Z")

</div>

Took me some time to figure out. Have combined codes from multiple sources. Can be used by beginners to learn client connection in go:

> package main
> 
> import (  
> “context”  
> “encoding/json”  
> “fmt”  
> “log”  
> “time”  
> “[github.com/dgraph-io/dgo/v200](http://github.com/dgraph-io/dgo/v200)”  
> “[github.com/dgraph-io/dgo/v200/protos/api](http://github.com/dgraph-io/dgo/v200/protos/api)”  
> “[grpc package - google.golang.org/grpc - Go Packages](http://google.golang.org/grpc)”  
> )
> 
> type School struct {  
> Name string `json:"name,omitempty"`  
> DType string `json:"dgraph.type,omitempty"`  
> }
> 
> type loc struct {  
> Type string `json:"type,omitempty"`  
> Coords float64 `json:"coordinates,omitempty"`  
> }
> 
> // If omitempty is not set, then edges with empty values (0 for int/float, “” for string, false  
> // for bool) would be created for values not specified explicitly.
> 
> type Person struct {  
> Uid string `json:"uid,omitempty"`  
> Name string `json:"name,omitempty"`  
> Age int `json:"age,omitempty"`  
> Dob \*time.Time `json:"dob,omitempty"`  
> Married bool `json:"married,omitempty"`  
> Raw byte `json:"raw_bytes,omitempty"`  
> Friends Person `json:"friend,omitempty"`  
> Location loc `json:"loc,omitempty"`  
> School School `json:"school,omitempty"`  
> DType string `json:"dgraph.type,omitempty"`  
> }  
> type CancelFunc func()
> 
> func getDgraphClient() (\*dgo.Dgraph, CancelFunc) {  
> conn, err := grpc.Dial(“127.0.0.1:9080”, grpc.WithInsecure())  
> if err != nil {  
> log.Fatal(“While trying to dial gRPC”)  
> }
> 
> dc := api.NewDgraphClient(conn)  
> dg := dgo.NewDgraphClient(dc)  
> // ctx := context.Background()
> 
> // Perform login call. If the Dgraph cluster does not have ACL and  
> // enterprise features enabled, this call should be skipped.  
> // for {  
> // Keep retrying until we succeed or receive a non-retriable error.  
> // err = dg.Login(ctx, “groot”, “password”)  
> // if err == nil || !strings.Contains(err.Error(), “Please retry”) {  
> // break  
> // }  
> // time.Sleep(time.Second)  
> // }  
> // if err != nil {  
> // log.Fatalf(“While trying to login %v”, err.Error())  
> // }
> 
> return dg, func() {  
> if err := conn.Close(); err != nil {  
> log.Printf(“Error while closing connection:%v”, err)  
> }  
> }  
> }
> 
> func main() {  
> dg, cancel := getDgraphClient()  
> defer cancel()
> 
> ```
> dob := time.Date(1980, 01, 01, 23, 0, 0, 0, time.UTC)
> // While setting an object if a struct has a Uid then its properties in the graph are updated
> // else a new node is created.
> // In the example below new nodes for Alice, Bob and Charlie and school are created (since they
> // don't have a Uid).
> p := Person{
> Uid: "_:alice",
> Name: "Alice",
> Age: 26,
> Married: true,
> DType: []string{"Person"},
> Location: loc{
> Type: "Point",
> Coords: []float64{1.1, 2},
> },
> Dob: &dob,
> Raw: []byte("raw_bytes"),
> Friends: []Person{{
> Name: "Bob",
> Age: 24,
> DType: []string{"Person"},
> }, {
> Name: "Charlie",
> Age: 29,
> DType: []string{"Person"},
> }},
> School: []School{{
> Name: "Crown Public School",
> DType: []string{"Institution"},
> }},
> }
> 
> op := &api.Operation{}
> op.Schema = `
> name: string @index(exact) .
> age: int .
> married: bool .
> loc: geo .
> dob: datetime .
> Friend: [uid] .
> type: string .
> coords: float .
> 
> type Person {
> name: string
> age: int
> married: bool
> Friend: [Person]
> loc: Loc
> }
> 
> type Institution {
> name: string
> }
> 
> type Loc {
> type: string
> coords: float
> }
> 
> ```
> 
> `
> 
> ```
> ctx := context.Background()
> if err := dg.Alter(ctx, op); err != nil {
> log.Fatal(err)
> }
> 
> mu := &api.Mutation{
> CommitNow: true,
> }
> pb, err := json.Marshal(p)
> if err != nil {
> log.Fatal(err)
> }
> 
> mu.SetJson = pb
> response, err := dg.NewTxn().Mutate(ctx, mu)
> if err != nil {
> log.Fatal(err)
> }
> 
> // Assigned uids for nodes which were created would be returned in the response.Uids map.
> variables := map[string]string{"$id1": response.Uids["alice"]}
> q := `query Me($id1: string){
> me(func: uid($id1)) {
> name
> dob
> age
> loc
> raw_bytes
> married
> dgraph.type
> friend @filter(eq(name, "Bob")){
> name
> age
> dgraph.type
> }
> school {
> name
> dgraph.type
> }
> }
> 
> ```
> 
> }`
> 
> ```
> resp, err := dg.NewTxn().QueryWithVars(ctx, q, variables)
> if err != nil {
> log.Fatal(err)
> }
> 
> type Root struct {
> Me []Person `json:"me"`
> }
> 
> var r Root
> err = json.Unmarshal(resp.Json, &r)
> if err != nil {
> log.Fatal(err)
> }
> 
> out, _ := json.MarshalIndent(r, "", "\t")
> fmt.Printf("%s\n", out)
> 
> ```
> 
> }

---

<div class="post-metadata">

**Author:** ![Paras](https://yyz1.discourse-cdn.com/flex007/user_avatar/discuss.dgraph.io/paras/32/2768_2.png) [@Paras](https://discuss.dgraph.io/u/Paras)\
**Post date:** [June 16, 2020, 3:29am UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213/2 "2020-06-16T03:29:09Z")

</div>

Thanks Deepak and welcome to the community!

We also have a full working example use of `dgo` at [https://dgraph.io/docs/clients/#complete-example](https://dgraph.io/docs/clients/#complete-example)

PS: Your post is not properly marked-down for code. Please rectify so the community can benefit.

---

<div class="post-metadata">

**Author:** ![trdeepak](https://yyz1.discourse-cdn.com/flex007/user_avatar/discuss.dgraph.io/trdeepak/32/3523_2.png) [@trdeepak](https://discuss.dgraph.io/u/trdeepak)\
**Post date:** [June 16, 2020, 4:20am UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213/3 "2020-06-16T04:20:21Z")

</div>

Right. But the example [https://dgraph.io/docs/clients/#complete-example](https://dgraph.io/docs/clients/#complete-example) calls the function getDgraphClient(), which is not available in the file. I took it from the test cases. You may want to update the example to that extent.

Regards

---

<div class="post-metadata">

**Author:** ![Paras](https://yyz1.discourse-cdn.com/flex007/user_avatar/discuss.dgraph.io/paras/32/2768_2.png) [@Paras](https://discuss.dgraph.io/u/Paras)\
**Post date:** [June 16, 2020, 4:58am UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213/4 "2020-06-16T04:58:25Z")

</div>

I don’t see it call `getDgraphClient()`. Am I missing something?

---

<div class="post-metadata">

**Author:** ![trdeepak](https://yyz1.discourse-cdn.com/flex007/user_avatar/discuss.dgraph.io/trdeepak/32/3523_2.png) [@trdeepak](https://discuss.dgraph.io/u/trdeepak)\
**Post date:** [June 17, 2020, 1:55pm UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213/5 "2020-06-17T13:55:42Z")

</div>

I was referring to the following link:  
[https://godoc.org/github.com/dgraph-io/dgo](https://godoc.org/github.com/dgraph-io/dgo)

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex007/uploads/dgraph/original/2X/2/2b38fdece2abe5814f2e51bee69d1e67fc304b0a.png) [@system](https://discuss.dgraph.io/u/system)\
**Post date:** [July 29, 2020, 5:55am UTC](https://discuss.dgraph.io/t/example-of-using-go-client-to-connect-to-dgraph/7213/6 "2020-07-29T05:55:48Z")

</div>

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.
