// Predict takes a request and response writer and proxies the request to
// the deployment associated with the provided id.
func (client *MPSClient) Predict(w http.ResponseWriter, r *http.Request, id int64) {
	q := r.URL.Query()
	q.Set("id", strconv.FormatInt(id, 10))
	r.URL.RawQuery = q.Encode()
	r.URL.Path = routePredict

	if wsutil.IsWebSocketRequest(r) {
		client.wsProxy.ServeHTTP(w, r)
	} else {
		client.httpProxy.ServeHTTP(w, r)
	}
}
Exemple #2
0
func (k *kernel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if wsutil.IsWebSocketRequest(r) {
		websocket.Handler(k.handleWS).ServeHTTP(w, r)
		return
	}

	switch r.Method {
	case "GET":

		// TODO: add more meta data to response such as model version
		err := k.heartbeat()
		resp := struct {
			Status string `json:"status"`
			Time   string `json:"date"`
		}{
			Time: time.Now().UTC().Format(time.RFC3339),
		}
		if err != nil {
			resp.Status = "ERROR"
		} else {
			resp.Status = "OK"
		}
		json.NewEncoder(w).Encode(&resp)
	case "POST":
		query := r.URL.Query()
		var data interface{}
		if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
			jsonError(w, "could not decode body: "+err.Error(), http.StatusBadRequest)
			return
		}
		resp, err := k.Predict(data, query)
		if err != nil {
			jsonError(w, "model experienced a fatal error "+err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		if _, ok := resp["result"]; !ok {
			w.WriteHeader(http.StatusInternalServerError)
		}
		json.NewEncoder(w).Encode(&resp)
	default:
		http.Error(w, "I only respond to GET and POSTs", http.StatusNotImplemented)
	}
}