Skip to content

Commit

Permalink
Move the API to use POST requests
Browse files Browse the repository at this point in the history
  • Loading branch information
jorgelbg committed Feb 21, 2020
1 parent 0591e20 commit 4d4ce6e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
28 changes: 20 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"html/template"
"net/http"
"net/url"
"strings"

"github.com/elastic/beats/libbeat/processors/dissect"
Expand All @@ -26,26 +27,35 @@ func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
str, ok := r.URL.Query()["str"]
if !ok || len(str[0]) == 0 {
err := r.ParseMultipartForm(1024 * 1024 * 16)
if err != nil {
http.Error(w, fmt.Sprintf("Couldn't parse POST request: %s", err.Error()),
http.StatusBadRequest)
return
}

str, _ := url.QueryUnescape(r.Form.Get("str"))
if len(str) == 0 {
http.Error(w, "samples parameter not found", http.StatusBadRequest)
return
}

tokenizer, ok := r.URL.Query()["tokenizer"]
if !ok || len(tokenizer[0]) < 1 {
tokenizer, _ := url.QueryUnescape(r.Form.Get("tokenizer"))
if len(tokenizer) == 0 {
http.Error(w, "pattern parameter not found", http.StatusBadRequest)
return
}

logger.Sugar().Infow("Received request",
"str", str[0],
"tokenizer", tokenizer[0],
"str", str,
"tokenizer", tokenizer,
)

samples := strings.Split(str[0], "\n")
samples := strings.Split(str, "\n")

tokenized := make([]map[string]string, 0)
for i, s := range samples {
processor, err := dissect.New(tokenizer[0])
processor, err := dissect.New(tokenizer)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
Expand All @@ -63,6 +73,7 @@ func main() {
payload, err := json.Marshal(tokenized)
if err != nil {
http.Error(w, "couldn't encode response", http.StatusNoContent)
return
}

w.Header().Set("Content-Type", "application/json")
Expand All @@ -72,5 +83,6 @@ func main() {
logger.Sugar().Infow("Server is running",
"port", 8080,
)

http.ListenAndServe(":8080", nil)
}
15 changes: 9 additions & 6 deletions static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ function testSamples() {
let resultTextArea = document.querySelector("#results");

let url = new URL(API_URL);
let params = {
tokenizer: pattern,
str: samples
};

Object.keys(params).forEach(k => url.searchParams.append(k, params[k]));
let body = new FormData();
body.append("tokenizer", encodeURIComponent(pattern));
body.append("str", encodeURIComponent(samples));

fetch(url)
fetch(url, {
method: "POST",
cache: "no-cache",
headers: { "Content-Encoding": "multipart/form-data" },
body: body
})
.then(res => {
if (res.ok) {
return res.json();
Expand Down

0 comments on commit 4d4ce6e

Please sign in to comment.