package udrclient import ( "bytes" "encoding/json" l "gitlab.com/cyclops-utilities/logging" "io/ioutil" "net/http" ) // The UDRRecord is reasonably self-explanaroy - the one point that is a little // non-obvious is the data field - this can be populated using code such as the // following: // // d := map[string]interface{}{ // "UID": "1", // "numberData": 200, // } // // and setting this equal to the data field in the struct. Note that this // implementation requires a bit more work to support embedding entire objects // within the Data field. // type UDRRecord struct { Metric string `json:"metric"` Account string `json:"account"` Usage float64 `json:"usage"` Time int64 `json:"time"` Data map[string]interface{} `json:"data"` Unit string `json:"unit"` } // UDRService simply contains the endpoint where the UDR service lives... // It is implemented as an interface which includes a PostCommand... type UDRService struct { Endpoint string } // PostRecord takes a UDRRecord and posts it to the UDR endpoint func (u *UDRService) PostRecord(r UDRRecord) (success bool, err error) { val, _ := json.Marshal(r) // fmt.Printf("r= %+v\n", string(val)) req, err := http.NewRequest("POST", u.Endpoint, bytes.NewBuffer(val)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { //panic(err) l.Error.Printf("error = %v\n", err.Error()) success = false return } defer resp.Body.Close() if err == nil { if resp.StatusCode != http.StatusCreated { l.Warning.Printf("Unexpected response POSTing to UDR - Response Status: %v\n", resp.Status) body, _ := ioutil.ReadAll(resp.Body) l.Debug.Printf("Response Body: %v\n", string(body)) success = false } else { // this is the successful case - only dump output if in debug mode as this // should be the default... body, _ := ioutil.ReadAll(resp.Body) l.Debug.Printf("Sending to Cyclops UDR service - Response Status: %v, Response Body: %v\n", resp.Status, string(body)) success = true } } return }