2019-06-10 17:09:10 +00:00
|
|
|
package amclient
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2019-06-11 18:07:43 +00:00
|
|
|
"log"
|
2019-06-10 17:09:10 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2019-06-11 04:31:04 +00:00
|
|
|
"time"
|
2019-06-10 17:09:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
2019-06-11 04:31:04 +00:00
|
|
|
reportURL string
|
2019-06-10 17:09:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// addr is the full address, for example: https://x.io/report.
|
2019-06-11 04:31:04 +00:00
|
|
|
func New(reportURL string) Client {
|
|
|
|
return Client{reportURL}
|
2019-06-10 17:09:10 +00:00
|
|
|
}
|
|
|
|
|
2019-06-11 04:31:04 +00:00
|
|
|
func (client Client) post(values url.Values) error {
|
|
|
|
cl := http.Client{Timeout: 30 * time.Second}
|
|
|
|
|
|
|
|
resp, err := cl.PostForm(client.reportURL, values)
|
2019-06-10 17:09:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return fmt.Errorf("POST failed: [%d] %s", resp.StatusCode, body)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cl Client) Ping() error {
|
2019-06-11 18:07:43 +00:00
|
|
|
if cl.reportURL == "" {
|
|
|
|
log.Printf("AM ping")
|
|
|
|
return nil
|
|
|
|
}
|
2019-06-10 17:09:10 +00:00
|
|
|
return cl.post(url.Values{
|
|
|
|
"action": []string{"ping"},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-06-11 09:55:52 +00:00
|
|
|
func (cl Client) Log(text string, args ...interface{}) error {
|
|
|
|
text = fmt.Sprintf(text, args...)
|
2019-06-11 18:07:43 +00:00
|
|
|
if cl.reportURL == "" {
|
|
|
|
log.Printf("AM log: %s", text)
|
|
|
|
return nil
|
|
|
|
}
|
2019-06-10 17:09:10 +00:00
|
|
|
return cl.post(url.Values{
|
|
|
|
"action": []string{"log"},
|
|
|
|
"text": []string{text},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-06-11 09:55:52 +00:00
|
|
|
func (cl Client) Alert(text string, args ...interface{}) error {
|
|
|
|
text = fmt.Sprintf(text, args...)
|
2019-06-11 18:07:43 +00:00
|
|
|
if cl.reportURL == "" {
|
|
|
|
log.Printf("AM alert: %s", text)
|
|
|
|
return nil
|
|
|
|
}
|
2019-06-10 17:09:10 +00:00
|
|
|
return cl.post(url.Values{
|
|
|
|
"action": []string{"alert"},
|
|
|
|
"text": []string{text},
|
|
|
|
})
|
|
|
|
}
|