-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
140 lines (128 loc) · 3.74 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"awesomeProject/proto"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/graphql-go/graphql"
gqlhandler "github.com/graphql-go/graphql-go-handler"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"io/ioutil"
"log"
"net"
"net/http"
)
type grpcServer struct {}
func main() {
listener, err := net.Listen("tcp", ":4040")
if err != nil {
log.Fatalf("failed to listen at port tcp:4040, error: %v", err)
}
grpcSrv := grpc.NewServer()
proto.RegisterDetectionCRUDServer(grpcSrv, &grpcServer{})
reflection.Register(grpcSrv)
go grpcSrv.Serve(listener)
log.Println("GRPC API started at :4040")
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(
createQueryType(
createDetectionType(),
),
),
})
if err != nil {
log.Fatalf("failed to create new schema, error: %v", err)
}
handler := gqlhandler.New(&gqlhandler.Config{
Schema: &schema,
GraphiQL:true,
})
http.Handle("/graphql", CorsMiddleware(handler))
log.Println("GraphQL API started at :8091/graphql")
log.Fatal(http.ListenAndServe(":8091", nil))
}
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// allow cross domain AJAX requests
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next.ServeHTTP(w,r)
})
}
type DetectionMetadata struct {
Id string `json:"id"`
XCoordinate string `json:"x_coordinate"`
YCoordinate string `json:"y_coordinate"`
BodyPart string `json:"bodyPart"`
Timestamp string `json:"timestamp"`
}
func createQueryType(detectionType *graphql.Object) graphql.ObjectConfig {
return graphql.ObjectConfig{Name: "QueryType", Fields: graphql.Fields{
"detection": &graphql.Field{
Type: detectionType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.Int),
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := p.Args["id"]
v, _ := id.(int)
log.Printf("fetching detection metadata with id: %d", v)
return fetchDetectionFromElastic(v)
},
},
}}
}
func createDetectionType() *graphql.Object {
return graphql.NewObject(graphql.ObjectConfig{
Name: "DetectionMetadata",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.NewNonNull(graphql.Int),
},
"x_coordinate": &graphql.Field{
Type: graphql.String,
},
"y_coordinate": &graphql.Field{
Type: graphql.String,
},
"bodyPart": &graphql.Field{
Type: graphql.String,
},
"timestamp": &graphql.Field{
Type: graphql.String,
},
},
})
}
func (s *grpcServer) Get(ctx context.Context, request *proto.DetectionRequest) (*proto.DetectionResponse, error) {
detection, err := fetchDetectionFromElastic(int(request.GetId()))
if err != nil {
log.Fatalf("failed to fetch detection, error: %v", err)
}
protoDetection := proto.Detection{Id:detection.Id, XCoordinate:detection.XCoordinate,YCoordinate:detection.YCoordinate,BodyPart:detection.BodyPart,Timestamp:detection.Timestamp}
return &proto.DetectionResponse{Detection:&protoDetection},nil
}
func fetchDetectionFromElastic(id int) (*DetectionMetadata, error) {
resp, err := http.Get(fmt.Sprintf("http://localhost:9200/detection/stream/_search=id:%d", id))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%s: %s", "Error: ", resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.New("error by parsing data")
}
result := DetectionMetadata{}
err = json.Unmarshal(b, &result)
if err != nil {
return nil, errors.New("error by unmarshal data")
}
return &result, nil
}