-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
83 lines (68 loc) · 1.82 KB
/
handlers.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
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"github.com/harrydrippin/brusta-go/model"
)
var m *model.Model
var singleton sync.Once
const (
modelPath = "./trace_model.pth"
modelOutputSize = 1
)
// HandlerRoot handles `/` route
func HandlerRoot(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Brusta-Go v1.0.0, Use `POST /predict` to inference"))
}
// HandlerPredict handles `/predict` route
func HandlerPredict(w http.ResponseWriter, r *http.Request) {
type HandlerPredictReq struct {
Input []float32 `json:"input"`
}
type HandlerPredictResp struct {
Result bool `json:"result"`
Output []float32 `json:"output,omitempty"`
Cause string `json:"cause,omitempty"`
}
var request HandlerPredictReq
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
log.Println("Predict: Input JSON is malformed")
w.WriteHeader(http.StatusBadRequest)
result := HandlerPredictResp{
Result: false,
Cause: "Input JSON is malformed",
}
if err := json.NewEncoder(w).Encode(&result); err != nil {
log.Println("Predict: Error occurred while processing error message")
}
return
}
if len(request.Input) == 0 {
result := HandlerPredictResp{
Result: false,
Cause: "Input is not provided",
}
if err := json.NewEncoder(w).Encode(&result); err != nil {
log.Println("Predict: Error occurred while processing error message")
}
return
}
singleton.Do(func() {
log.Println("Initializing model")
m = model.GetModel(modelPath, modelOutputSize)
})
output := m.Predict(request.Input)
response := HandlerPredictResp{
Result: true,
Output: output,
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(&response); err != nil {
log.Println("Predict: Error occurred while processing response")
return
}
return
}