-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsentiment.go
69 lines (56 loc) · 1.3 KB
/
sentiment.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
package main
import (
"encoding/json"
"errors"
"net/http"
"os"
"strings"
"time"
"github.com/dghubble/sling"
)
const (
baseURL = "https://language.googleapis.com/v1/documents:analyzeSentiment"
)
type SentSvc interface {
Score(corpus []string) (float64, float64)
}
type sentSvc struct {
sling *sling.Sling
httpClient *http.Client
}
func (s *sentSvc) Score(corpus []string) (float64, float64) {
content := strings.Join(corpus, ".")
body := NewSentimentRequest(content)
req, err := s.sling.BodyJSON(body).Request()
if err != nil {
panic(err.Error())
}
res, err := s.httpClient.Do(req)
if err != nil || res.StatusCode != http.StatusOK {
panic(err.Error())
}
defer res.Body.Close()
sentRes := sentimentResponse{}
json.NewDecoder(res.Body).Decode(&sentRes)
return sentRes.DocumentSentiment.Score,
sentRes.DocumentSentiment.Magnitude
}
type params struct {
Key string `url:"key,omitempty"`
}
func NewSentSvc() SentSvc {
auth, ok := os.LookupEnv("NLP_API_KEY")
if !ok {
panic(errors.New("bad auth data for cloud nlp api"))
}
sling := sling.
New().
Set("Content-Type", "application/json; charset=utf-8").
Post(baseURL).
QueryStruct(¶ms{Key: auth})
httpClient := http.Client{Timeout: time.Second * 10}
return &sentSvc{
sling: sling,
httpClient: &httpClient,
}
}