-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
101 lines (80 loc) · 2.29 KB
/
api.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
package api
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/soeffing/nlp/downloader"
"github.com/soeffing/nlp/rake"
"github.com/soeffing/nlp/sparql"
"html/template"
"net/http"
"strings"
)
// Greeting is simple data structure for static page
type Greeting struct {
Message string
}
type downloadRequestParams struct {
Urls []string
}
type sparqlRequestParams struct {
Term string
}
func staticHandler(w http.ResponseWriter, r *http.Request) {
// TODO: find better way to parse URL params
// mux.Vars not working with go 1.7
msg := strings.Split(r.URL.Path, "/")[2]
data := &Greeting{Message: msg}
t, _ := template.ParseFiles("tmpl/static.html")
t.Execute(w, data)
}
func downloadHandler(w http.ResponseWriter, r *http.Request) {
// set proper header
// TODO: use some sort of pre-hook to set those
w.Header().Set("Content-Type", "application/json")
var params downloadRequestParams
err := json.NewDecoder(r.Body).Decode(¶ms)
defer r.Body.Close()
if err != nil {
panic(err)
}
downloader := downloader.New()
downloader.Download(params.Urls)
// Try out the json encoder
// json.NewEncoder(w).Encode(&pages)
jData, _ := json.Marshal(downloader.Pages)
w.Write(jData)
}
func sparqlHandler(w http.ResponseWriter, r *http.Request) {
// set proper header
// TODO: use some sort of pre-hook to set those
w.Header().Set("Content-Type", "application/json")
term := r.URL.Query().Get("term")
data, err := sparql.GetLabelAbstractByTerm(term)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
jData, _ := json.Marshal(data)
w.Write(jData)
}
func rakeHandler(w http.ResponseWriter, r *http.Request) {
// set proper header
// TODO: use some sort of pre-hook to set those
fmt.Println("enter rake handler")
w.Header().Set("Content-Type", "application/json")
text := r.URL.Query().Get("text")
fmt.Println(text)
candidateKeywords := rake.Run(text)
fmt.Println(candidateKeywords)
jData, _ := json.Marshal(candidateKeywords)
w.Write(jData)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/static/{greeting}", staticHandler)
r.HandleFunc("/api/download", downloadHandler).Methods("POST")
r.HandleFunc("/api/sparql", sparqlHandler).Methods("GET")
r.HandleFunc("/api/rake", rakeHandler).Methods("GET")
http.ListenAndServe(":8080", nil)
}