Created
June 15, 2021 12:26
-
-
Save gustavohenrique/f5de7679e158825558cf935809dc8a6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/dgraph-io/dgo/v210" | |
"github.com/dgraph-io/dgo/v210/protos/api" | |
"google.golang.org/grpc" | |
) | |
func client() *dgo.Dgraph { | |
conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn)) | |
return dgraphClient | |
} | |
func main() { | |
http.HandleFunc("/", hi) | |
http.HandleFunc("/api", doGET) | |
http.HandleFunc("/api/create", doPOST) | |
log.Println("Listening :8080") | |
log.Fatal(http.ListenAndServe(":9999", nil)) | |
} | |
func hi(w http.ResponseWriter, r *http.Request) { | |
name := "Gustavo" | |
fmt.Fprintf(w, "Hi, %s!", name) | |
} | |
func doGET(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
if r.Method != "GET" { | |
w.WriteHeader(http.StatusMethodNotAllowed) | |
w.Write([]byte(`{"message": "Method not allowed"}`)) | |
return | |
} | |
q := `{ | |
items(func: has(tweet)) { | |
uid | |
tweet | |
tagged_with { | |
uid | |
} | |
} | |
}` | |
c := client() | |
txn := c.NewReadOnlyTxn() | |
resp, err := txn.Query(context.Background(), q) | |
if err != nil { | |
log.Fatal(err) | |
} | |
w.WriteHeader(http.StatusOK) | |
w.Write(resp.GetJson()) | |
} | |
func doPOST(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
if r.Method != "POST" { | |
w.WriteHeader(http.StatusMethodNotAllowed) | |
w.Write([]byte(`{"message": "Method not allowed"}`)) | |
return | |
} | |
w.WriteHeader(http.StatusCreated) | |
w.Write([]byte(`{"data": "POST ok"}`)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment