github.com/rpdict/ponzu@v0.10.1-0.20190226054626-477f29d6bf5e/system/addon/api.go (about)

     1  // Package addon provides an API for Ponzu addons to interface with the system
     2  package addon
     3  
     4  import (
     5  	"bytes"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"log"
     9  	"net/http"
    10  	"time"
    11  
    12  	"github.com/rpdict/ponzu/system/db"
    13  )
    14  
    15  // QueryOptions is a mirror of the same struct in db package and are re-declared
    16  // here only to make the API simpler for the caller
    17  type QueryOptions db.QueryOptions
    18  
    19  // ContentAll retrives all items from the HTTP API within the provided namespace
    20  func ContentAll(namespace string) []byte {
    21  	addr := db.ConfigCache("bind_addr").(string)
    22  	port := db.ConfigCache("http_port").(string)
    23  	endpoint := "http://%s:%s/api/contents?type=%s&count=-1"
    24  	URL := fmt.Sprintf(endpoint, addr, port, namespace)
    25  
    26  	j, err := Get(URL)
    27  	if err != nil {
    28  		log.Println("Error in ContentAll for reference HTTP request:", URL)
    29  		return nil
    30  	}
    31  
    32  	return j
    33  }
    34  
    35  // Query retrieves a set of content from the HTTP API  based on options
    36  // and returns the total number of content in the namespace and the content
    37  func Query(namespace string, opts QueryOptions) []byte {
    38  	addr := db.ConfigCache("bind_addr").(string)
    39  	port := db.ConfigCache("http_port").(string)
    40  	endpoint := "http://%s:%s/api/contents?type=%s&count=%d&offset=%d&order=%s"
    41  	URL := fmt.Sprintf(endpoint, addr, port, namespace, opts.Count, opts.Offset, opts.Order)
    42  
    43  	j, err := Get(URL)
    44  	if err != nil {
    45  		log.Println("Error in Query for reference HTTP request:", URL)
    46  		return nil
    47  	}
    48  
    49  	return j
    50  }
    51  
    52  // Get is a helper function to make a HTTP call from an addon
    53  func Get(endpoint string) ([]byte, error) {
    54  	buf := []byte{}
    55  	r := bytes.NewReader(buf)
    56  
    57  	req, err := http.NewRequest(http.MethodGet, endpoint, r)
    58  	if err != nil {
    59  		log.Println("Error creating reference HTTP request:", endpoint)
    60  		return nil, err
    61  	}
    62  
    63  	c := http.Client{
    64  		Timeout: time.Duration(time.Second * 5),
    65  	}
    66  	res, err := c.Do(req)
    67  	if err != nil {
    68  		log.Println("Error making reference HTTP request:", endpoint)
    69  		return nil, err
    70  	}
    71  	defer res.Body.Close()
    72  
    73  	j, err := ioutil.ReadAll(res.Body)
    74  	if err != nil {
    75  		log.Println("Error reading body for reference HTTP request:", endpoint)
    76  		return nil, err
    77  	}
    78  
    79  	return j, nil
    80  }