// Package appstats is a helper for submitting events to stepladder's appstats module package appstats import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "os" "strconv" "time" log "github.com/sirupsen/logrus" ) const ( stagingURL = "https://staging.stepladder.rax.io/api/appstats/v3/event" productionURL = "https://stepladder.rax.io/api/appstats/v3/event" ) // Client : Main client type Client struct { name string source string url string version string } // APIResponse : Response from stepladder appstats event endpoint type APIResponse struct { Msg string `json:"msg"` CopiesInserted int `json:"copies_inserted"` Error bool `json:"error"` } // NewClient : Creates a new client with given identity token func NewClient(app, version, source string, staging bool) (*Client, error) { if len(app) == 0 { return nil, errors.New("appName cannot be empty") } if len(version) == 0 { return nil, errors.New("version cannot be empty") } if len(source) == 0 { return nil, errors.New("source cannot be empty") } c := &Client{ name: app, version: version, source: source, } if staging { c.url = stagingURL } else { c.url = productionURL } return c, nil } type EventPayload struct { App string `json:"app"` Function string `json:"function"` Username string `json:"username"` Date int64 `json:"date"` Source string `json:"source"` Version string `json:"version"` } func (c Client) Event(function, username string, date time.Time) error { data := EventPayload{ App: c.name, Function: function, Username: username, Source: c.source, Date: date.Unix(), Version: c.version, } jsonStr, err := json.Marshal(data) if err != nil { return err } req, err := http.NewRequest(http.MethodPost, c.url, bytes.NewBuffer(jsonStr)) if err != nil { return err } req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { return err } defer func() { if err := res.Body.Close(); err != nil { log.Error(err) } }() body, err := ioutil.ReadAll(res.Body) if err != nil { return err } if res.StatusCode != 200 { return fmt.Errorf("error from stepladder: %v - %s", res.StatusCode, string(body)) } var response APIResponse if err := json.Unmarshal(body, &response); err != nil { return err } if response.Error { return errors.New(response.Msg) } log.WithField("response", response).Debug("response from stepladder") return nil } func init() { debug, _ := strconv.ParseBool(os.Getenv("DEBUG")) if debug { log.SetLevel(log.DebugLevel) } }