doc stringlengths 10 26.3k | code stringlengths 52 3.87M |
|---|---|
// DatasetExists checks for the existence of a dataset | func DatasetExists(name string) bool {
err := exec.Command("zfs", "list", "-t", "filesystem", name).Run()
return err == nil
} |
// GetProperty returns a property for a dataset | func (ds *Dataset) GetProperty(property string) (string, error) {
out, err := exec.Command("zfs", "get", "-H",
"-o", "value",
property, ds.Name).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
} |
// CreateDatasetRecursive recursively creates a dataset | func CreateDatasetRecursive(name string, properties map[string]string) (*Dataset, error) {
return createDataset(name, true, properties)
} |
// CreateDataset creates a dataset | func CreateDataset(name string, properties map[string]string) (*Dataset, error) {
return createDataset(name, false, properties)
} |
// Destroy destroys a dataset | func (ds *Dataset) Destroy() error {
if err := exec.Command("zfs", "destroy", "-R", ds.Name).Run(); err != nil {
return err
}
return nil
} |
// GetSnapshot returns a snapshot from a string | func GetSnapshot(name string) (*Snapshot, error) {
if !SnapshotExists(name) {
return nil, fmt.Errorf("Snapshot not found")
}
return &Snapshot{
Name: name,
}, nil
} |
// SnapshotExists checks for the existence of a dataset | func SnapshotExists(Name string) bool {
err := exec.Command("zfs", "list", "-t", "snapshot", Name).Run()
return err == nil
} |
// Snapshot creates a snapshot | func (ds *Dataset) Snapshot(name string) (*Snapshot, error) {
sn := fmt.Sprintf("%v@%v", ds.Name, name)
err := exec.Command("zfs", "snapshot", sn).Run()
if err != nil {
return nil, err
}
return GetSnapshot(sn)
} |
// Clone clones a snapshot | func (sn *Snapshot) Clone(target string) (*Dataset, error) {
err := exec.Command("zfs", "clone", sn.Name, target).Run()
if err != nil {
return nil, err
}
return GetDataset(target)
} |
// NewPostgreSQLCluster creates Cluster. Drivername can be specified,
// but must point to a PostgreSQL driver. | func NewPostgreSQLCluster(drivername string, connStrings []string) (*Cluster, error) {
cleanUpDBs := func(dbs []*sql.DB) {
for _, db := range dbs {
db.Close()
}
}
dedup := make(map[string]struct{})
dbs := make([]*sql.DB, 0, len(connStrings))
if len(connStrings) == 0 {
return nil, ErrZeroDataSource
}
... |
// NOTE: SetConnMaxLifetime implement fot go1.6 only
// SetMaxIdleConns sets the maximum number of connections
// in the idle connection pool for each memeber of a cluster | func (c *Cluster) SetMaxIdleConns(n int) {
for _, db := range c.dbs {
db.SetMaxIdleConns(n)
}
} |
// SetMaxOpenConns sets the maximum number of open connections
// to the database for each memeber of a cluster | func (c *Cluster) SetMaxOpenConns(n int) {
for _, db := range c.dbs {
db.SetMaxOpenConns(n)
}
} |
// Close closes connections per each db contained in Cluster.
// An error fron each Close is collected. | func (c *Cluster) Close() error {
close(c.stopCh)
var errors []error
for _, db := range c.dbs {
if err := db.Close(); err != nil {
errors = append(errors, err)
}
}
if len(errors) != 0 {
return fmt.Errorf("%v", errors)
}
return nil
} |
// DB returns *sql.DB suggested to be a master in the cluster.
// Current implementation checks master every 5 seconds.
// However the proper approach is to reelect a master after disconnection error. | func (c *Cluster) DB(role Role) *sql.DB {
switch role {
case MASTER:
// It is always set. Even if there's no master at all.
return c.currentMaster.Load().(*sql.DB)
case SLAVE:
// TODO: NOT IMPLEMENTED
// It is always set. Even if there's no master at all.
return c.currentMaster.Load().(*sql.DB)
default:
... |
// Create an Annotation
//
// Librato API docs: https://www.librato.com/docs/api/?shell#create-an-Annotation | func (a *AnnotationsService) Create(annotation *Annotation) (*Annotation, *http.Response, error) {
u := fmt.Sprintf("annotations/%s", *annotation.Name)
req, err := a.client.NewRequest("POST", u, annotation)
if err != nil {
return nil, nil, err
}
an := new(Annotation)
resp, err := a.client.Do(req, an)
if err !... |
// SetConnMaxLifetime sets the maximum amount of time
// a connection may be reused for each memeber of a cluster | func (c *Cluster) SetConnMaxLifetime(d time.Duration) {
for _, db := range c.dbs {
db.SetConnMaxLifetime(d)
}
} |
// Note this is exactly what autoload.go does | func main() {
pwd, _ := os.Getwd()
env.ReadEnv(path.Join(pwd, ".env"))
for _, v := range os.Environ() {
fmt.Println(v)
}
} |
// GetDomains retrieves all the domains for a given account. | func (c *Client) GetDomains() ([]Domain, error) {
req, err := c.NewRequest(nil, "GET", "/domains")
if err != nil {
return nil, err
}
resp, err := c.Http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
domainResponses := []DomainResponse{}
err = decode(resp.Body, &domainResponses)
if err ... |
// MarkdownToText parses the markdown using the Blackfriday Markdown Processor
// and an internal renderer to return any metadata and the formatted text. If
// opt is nil the defaults will be used.
//
// See MarkdownMetadata for a description of the [][]string metadata returned. | func MarkdownToText(markdown []byte, opt *Options) ([][]string, []byte) {
metadata, position := MarkdownMetadata(markdown)
return metadata, MarkdownToTextNoMetadata(markdown[position:], opt)
} |
// MarkdownMetadata parses just the metadata from the markdown and returns the
// metadata and the position of the rest of the markdown.
//
// The metadata is a [][]string where each []string will have two elements, the
// metadata item name and the value. Metadata is an extension of standard
// Markdown and is documen... | func MarkdownMetadata(markdown []byte) ([][]string, int) {
var metadata [][]string
pos := 0
for _, line := range bytes.Split(markdown, []byte("\n")) {
sline := strings.Trim(string(line), " ")
if sline == "" {
break
}
colon := strings.Index(sline, ": ")
if colon == -1 {
// Since there's no blank line ... |
// MarkdownToTextNoMetadata is the same as MarkdownToText only skipping the
// detection and parsing of any leading metadata. If opts is nil the defaults
// will be used. | func MarkdownToTextNoMetadata(markdown []byte, opts *Options) []byte {
opts = resolveOpts(opts)
rend := &renderer{
width: opts.Width,
color: opts.Color,
tableAlignOptions: opts.TableAlignOptions,
headerPrefix: opts.HeaderPrefix,
headerSuffix: opts.HeaderSuffix,
}
markdown... |
// ConvertToConditionalUpdates converts a bundle containing POST requests to a bundle with PUT requests using
// conditional updates. For patient resources, the update is based on the Medical Record Number. For all other
// resources it is based on reasonable indicators of sameness (such as equal dates and codes). | func ConvertToConditionalUpdates(bundle *models.Bundle) error {
for _, entry := range bundle.Entry {
values := url.Values{}
switch t := entry.Resource.(type) {
case *models.AllergyIntolerance:
if check(t.Patient, t.Substance, t.Onset) {
addRefParam(values, "patient", t.Patient)
addCCParam(values, "sub... |
// Parses and compiles the contents of a supplied directory path, with options.
// Returns a map of a template identifier (key) to a Go Template instance.
// Ex: if the dirname="templates/" had a file "index.jade" the key would be "index"
// If option for recursive is True, this parses every file of relevant extension
... | func CompileDir(dirname string, dopt DirOptions, opt Options) (map[string]*template.Template, error) {
dir, err := os.Open(dirname)
if err != nil {
return nil, err
}
defer dir.Close()
files, err := dir.Readdir(0)
if err != nil {
return nil, err
}
compiled := make(map[string]*template.Template)
for _, fil... |
// Parse given raw jade template string. | func (c *Compiler) Parse(input string) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
parser, err := parser.StringParser(input)
parser.FileName(c.filename)
if err != nil {
return
}
c.node = parser.Parse()
return
} |
// Parse the jade template file in given path | func (c *Compiler) ParseFile(filename string) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
parser, err := parser.FileParser(filename)
if err != nil {
return
}
c.node = parser.Parse()
c.filename = filename
return
} |
// NewClient returns a new Librato API client bound to the public Librato API. | func NewClient(email, token string) *Client {
bu, err := url.Parse(defaultBaseURL)
if err != nil {
panic("Default Librato API base URL couldn't be parsed")
}
return NewClientWithBaseURL(bu, email, token)
} |
// NewClientWithBaseURL returned a new Librato API client with a custom base URL. | func NewClientWithBaseURL(baseURL *url.URL, email, token string) *Client {
headers := map[string]string{
"Content-Type": defaultMediaType,
"Accept": defaultMediaType,
}
c := &Client{
client: http.DefaultClient,
Headers: headers,
Email: email,
Token: token,
BaseURL: baseURL,
User... |
// NewRequest creates an API request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.... | func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
encodeErr := json.NewEncoder(buf).Encode(body)
... |
// RenderErrorFromArray returns a string with the parameter errors | func RenderErrorFromArray(errors []interface{}) string {
buf := new(bytes.Buffer)
for _, err := range errors {
fmt.Fprintf(buf, " %s,", err.(string))
}
return buf.String()
} |
// RenderErrorFromMap returns a string with the parameter errors
// (e.g. from Conditions) | func RenderErrorFromMap(errors map[string]interface{}) string {
buf := new(bytes.Buffer)
for cond, condErrs := range errors {
fmt.Fprintf(buf, " %s:", cond)
for _, err := range condErrs.([]interface{}) {
fmt.Fprintf(buf, " %s,", err.(string))
}
}
return buf.String()
} |
// Float is a helper routine that allocates a new float64 value
// to store v and returns a pointer to it. | func Float(v float64) *float64 {
p := new(float64)
*p = v
return p
} |
// Get an alert by ID
//
// Librato API docs: https://www.librato.com/docs/api/#retrieve-alert-by-id | func (a *AlertsService) Get(id uint) (*Alert, *http.Response, error) {
urlStr := fmt.Sprintf("alerts/%d", id)
req, err := a.client.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, nil, err
}
alert := new(Alert)
resp, err := a.client.Do(req, alert)
if err != nil {
return nil, resp, err
}
return... |
// Create an alert
//
// Librato API docs: https://www.librato.com/docs/api/?shell#create-an-alert | func (a *AlertsService) Create(alert *Alert) (*Alert, *http.Response, error) {
req, err := a.client.NewRequest("POST", "alerts", alert)
if err != nil {
return nil, nil, err
}
al := new(Alert)
resp, err := a.client.Do(req, al)
if err != nil {
return nil, resp, err
}
return al, resp, err
} |
// Update an alert.
//
// Librato API docs: https://www.librato.com/docs/api/?shell#update-alert | func (a *AlertsService) Update(alertID uint, alert *Alert) (*http.Response, error) {
u := fmt.Sprintf("alerts/%d", alertID)
req, err := a.client.NewRequest("PUT", u, alert)
if err != nil {
return nil, err
}
return a.client.Do(req, nil)
} |
// Delete an alert
//
// Librato API docs: https://www.librato.com/docs/api/?shell#delete-alert | func (a *AlertsService) Delete(id uint) (*http.Response, error) {
u := fmt.Sprintf("alerts/%d", id)
req, err := a.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return a.client.Do(req, nil)
} |
// CreateFilesystem runs zfs create | func CreateFilesystem(name string, opts *CreateFilesystemOpts) error {
cmd := newCmd("create")
if opts != nil {
cmd = addOpt(cmd, opts.DontMount, "-u")
cmd = addOpt(cmd, opts.CreateParents, "-p")
cmd = addProperties(cmd, opts.SetProperties)
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
} |
// CreateVolue runs zfs create -V | func CreateVolue(name, size string, opts *CreateVolumeOpts) error {
cmd := newCmd("create")
cmd = addOpt(cmd, true, "-V", size)
if opts != nil {
cmd = addProperties(cmd, opts.SetProperties)
cmd = addOpt(cmd, opts.BlockSize != "", "-b", opts.BlockSize)
cmd = addOpt(cmd, opts.Sparse, "-s")
}
cmd = addNonEmpty(... |
// Destroy runs zfs destroy | func Destroy(name string, opts *DestroyOpts) error {
cmd := newCmd("destroy")
if opts != nil {
cmd = addOpt(cmd, opts.DestroyChildren, "-r")
cmd = addOpt(cmd, opts.DestroyClones, "-R")
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
cmd = addOpt(cmd, opts.Defer, "-d")
}
cmd = addNonEmpty(cmd, name)
return zExec... |
// Snapshot runs zfs snapshot | func Snapshot(name string, opts *SnapshotOpts) error {
cmd := newCmd("snapshot")
if opts != nil {
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addProperties(cmd, opts.SetProperties)
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
} |
// Rollback runs zfs rollback | func Rollback(name string, opts *RollbackOpts) error {
cmd := newCmd("rollback")
if opts != nil {
cmd = addOpt(cmd, opts.DestroyLaterSnapshots, "-r")
cmd = addOpt(cmd, opts.DestroyClones, "-R")
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
} |
// Clone runs zfs clone | func Clone(snapshot, name string, opts *CloneOpts) error {
cmd := newCmd("clone")
if opts != nil {
cmd = addOpt(cmd, opts.CreateParents, "-p")
cmd = addProperties(cmd, opts.SetProperties)
}
cmd = addNonEmpty(cmd, snapshot, name)
return zExecNoOut(cmd)
} |
// Rename runs zfs rename | func Rename(name, newName string, opts *RenameOpts) error {
cmd := newCmd("rename")
if opts != nil {
cmd = addOpt(cmd, opts.CreateParents, "-p")
cmd = addOpt(cmd, opts.DontReMount, "-u")
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
cmd = addOpt(cmd, opts.Recurse, "-r")
}
cmd = addNonEmpty(cmd, name, newName)
... |
// List runs zfs list
// Returns a map indexed by dataset name, which holds maps of the requested properties | func List(name string, opts *ListOpts) ([]string, error) {
cmd := newCmd("list", "-Hp")
if opts == nil {
opts = &ListOpts{}
}
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addOpt(cmd, opts.Depth != -1, "-d", fmt.Sprintf("%d", opts.Depth))
cmd = addCommaSeparatedOption(cmd, "-o", []string{"name"})
cmd = addCommaS... |
// Set runs zfs set | func Set(name string, properties map[string]string) error {
cmd := newCmd("set")
cmd = addSetProperties(cmd, properties)
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
} |
// Get runs zfs get
// Returns a map indexed by dataset, each of which holds a map indexed by the requested property | func Get(name string, properties []string, opts *GetOpts) (map[string]map[string]*Property, error) {
cmd := newCmd("get", "-Hp")
if opts == nil {
opts = &GetOpts{}
}
if len(properties) == 0 {
properties = []string{"name"}
}
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addOpt(cmd, opts.Depth != -1, "-d", fmt.... |
// Inherit runs zfs inherit | func Inherit(name string, property string, opts *InheritOpts) error {
cmd := newCmd("inherit")
if opts != nil {
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addOpt(cmd, opts.Received, "-S")
}
cmd = addNonEmpty(cmd, property, name)
return zExecNoOut(cmd)
} |
// GetMounts runs zfs mount with no arguments | func GetMounts() ([]*MountEntry, error) {
cmd := newCmd("mount")
out, err := zExec(cmd)
if err != nil {
return nil, err
}
ret := []*MountEntry{}
for _, l := range strings.Split(string(out), "\n") {
d := strings.SplitN(l, " ", 2)
ret = append(ret, &MountEntry{
Name: strings.Trim(d[0], " "),
Moun... |
// Mount runs zfs mount | func Mount(name string, opts *MountOpts) error {
cmd := newCmd("mount")
if opts != nil {
cmd = addCommaSeparatedOption(cmd, "-o", opts.Properties)
cmd = addOpt(cmd, opts.MountAll, "-a")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
} |
// UnMount runs zfs unmount | func UnMount(name string, opts *UnMountOpts) error {
cmd := newCmd("unmount")
if opts != nil {
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
cmd = addOpt(cmd, opts.UnMountAll, "-a")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
} |
// Bookmark runs zfs bookmark | func Bookmark(snapshot, bookmark string) error {
cmd := newCmd("bookmark", snapshot, bookmark)
return zExecNoOut(cmd)
} |
// GetWith will call .New(...); .Show() and returns .Get() | func GetWith(name string, options []string) string {
l := New(name, options)
l.Show()
return l.Get()
} |
// New returns a list initialized with Default theme. | func New(name string, options []string) *List {
list := &List{}
list.name = name
list.options = options
list.Index = 0
list.Cursor = &curse.Cursor{}
list.SetColors(DefaultColors)
list.SetPrint(fmt.Print)
list.SetChooser(" ❯ ")
list.SetIndent(3)
return list
} |
// SetIndent sets indent before options | func (list *List) SetIndent(indent int) {
list.indent = "" + strings.Repeat(" ", indent)
} |
// PrintHighlight prints highlighted list element | func (list *List) PrintHighlight(element string) int {
newIndent := len(list.indent) - 3
indent := ""
if newIndent > 1 {
indent = strings.Repeat(" ", newIndent)
}
list.colors.Highlight.Set()
bytes, _ := list.Print(indent + list.chooser + element)
color.Unset()
return bytes
} |
// PrintOption prints list option | func (list *List) PrintOption(option string) int {
list.colors.Option.Set()
bytes, _ := list.Print(list.indent + option)
color.Unset()
return bytes
} |
// PrintHead prints list header | func (list *List) PrintHead() int {
list.colors.Head.Set()
bytes, _ := list.Print(list.name)
color.Unset()
return bytes
} |
// PrintResult prints list header and choosen option | func (list *List) PrintResult(result string) int {
var bytes int
bytes = list.PrintHead()
list.colors.Highlight.Set()
printBytes, _ := list.Print(" ", result)
color.Unset()
return bytes + printBytes + list.Println()
} |
// ShowOptions shows options | func (list *List) ShowOptions() int {
result := 0
for Index, element := range list.options {
if Index == 0 {
result += list.PrintHighlight(element) + list.Println()
continue
}
result += list.PrintOption(element) + list.Println()
}
list.Index = 1
list.Cursor.MoveUp(len(list.options))
return result
... |
// ClearOptions clears options from console | func (list *List) ClearOptions() {
length := len(list.options)
diff := length - list.Index
// Move to the last line.
if diff != 0 {
list.Cursor.MoveDown(diff)
}
list.Index = length
// Erase options
for list.Index != 0 {
list.Index--
list.Cursor.EraseCurrentLine()
list.Cursor.MoveUp(1)
}
} |
// Enter key handler | func (list *List) Enter() string {
result := list.options[list.Index-1]
list.ClearOptions()
list.PrintResult(result)
list.Print(ShowCursor)
return result
} |
// Exit Ctrl + (C | D | Z) and alike handler | func (list *List) Exit() {
// Should go down to the last option
for list.Index != len(list.options) {
list.Index++
list.Cursor.MoveDown(1)
}
list.Println()
list.Println()
list.Print(ShowCursor)
os.Exit(1)
} |
// HighlightUp highlights option above | func (list *List) HighlightUp() *List {
// If there is no where to go
if 0 >= list.Index-1 {
return list
}
list.Cursor.EraseCurrentLine()
list.PrintOption(list.options[list.Index-1])
list.Cursor.MoveUp(1)
list.Cursor.EraseCurrentLine()
list.Index--
list.PrintHighlight(list.options[list.Index-1])
return... |
// HighlightDown highlights option below | func (list *List) HighlightDown() *List {
// If there is no where to go
if len(list.options) < list.Index+1 {
return list
}
list.Cursor.EraseCurrentLine()
list.PrintOption(list.options[list.Index-1])
list.Cursor.MoveDown(1)
list.Cursor.EraseCurrentLine()
list.PrintHighlight(list.options[list.Index])
lis... |
// convertClinicalStatus maps the clinical status to a code in the "preferred" FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-condition-clinical.html
// If the status cannot be reliably mapped, an empty code will be returned. | func (c *Condition) convertClinicalStatus() string {
var status string
statusConcept := c.StatusCode.FHIRCodeableConcept("")
switch {
case statusConcept.MatchesCode("http://snomed.info/sct", "55561003"):
status = "active"
case statusConcept.MatchesCode("http://snomed.info/sct", "73425007"):
status = "remission... |
// convertSeverity maps the severity to a CodeableConcept. If possible, it will add a display name.
// FHIR has a "preferred" value set for severity:
// http://hl7.org/fhir/DSTU2/valueset-condition-severity.html
// Note that this is a subset of the value set that is often used:
// https://phinvads.cdc.gov/vads/View... | func (c *Condition) convertSeverity() *fhir.CodeableConcept {
if len(c.Severity) == 0 {
return nil
}
severity := c.Severity.FHIRCodeableConcept("")
switch {
case severity.MatchesCode("http://snomed.info/sct", "399166001"):
severity.Text = "Fatal"
case severity.MatchesCode("http://snomed.info/sct", "255604002... |
// NewDataClient creates a new DataClient for talking to the Read API | func NewDataClient(url string, logger *logrus.Logger, options ...Option) DataClient {
return &defaultDataClient{
URL: url,
log: logger,
options: options,
}
} |
// CreateChart creates a chart in a given Librato Space.
//
// Librato API docs: http://dev.librato.com/v1/post/spaces/:id/charts | func (s *SpacesService) CreateChart(spaceID uint, chart *SpaceChart) (*SpaceChart, *http.Response, error) {
u := fmt.Sprintf("spaces/%d/charts", spaceID)
req, err := s.client.NewRequest("POST", u, chart)
if err != nil {
return nil, nil, err
}
c := new(SpaceChart)
resp, err := s.client.Do(req, c)
if err != nil... |
// ListCharts lists all charts in a given Librato Space.
//
// Librato API docs: http://dev.librato.com/v1/get/spaces/:id/charts | func (s *SpacesService) ListCharts(spaceID uint) ([]SpaceChart, *http.Response, error) {
u := fmt.Sprintf("spaces/%d/charts", spaceID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
charts := new([]SpaceChart)
resp, err := s.client.Do(req, charts)
if err != nil {
retur... |
// DeleteChart deletes a chart.
//
// Librato API docs: http://dev.librato.com/v1/delete/spaces/:id/charts/:id | func (s *SpacesService) DeleteChart(spaceID, chartID uint) (*http.Response, error) {
u := fmt.Sprintf("spaces/%d/charts/%d", spaceID, chartID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
} |
// NewSinkHandler creates SinkHandler with sink channel buffer size bufSize that wraps inner handler for writing logs.
// When SinkHandler is created a go routine is started. When not used always call Close to terminate go routine. | func NewSinkHandler(inner Handler, bufSize int) *SinkHandler {
b := &SinkHandler{
inner: inner,
sinkCh: make(chan *Record, bufSize),
bufSize: bufSize,
}
b.wg.Add(1)
go b.process()
return b
} |
// process reads log records from sinkCh and calls inner log handler to write it. | func (b *SinkHandler) process() {
for {
rec, ok := <-b.sinkCh
if !ok {
b.inner.Close()
break
}
b.inner.Handle(rec)
}
b.wg.Done()
} |
// Status reports sink capacity and length. | func (b *SinkHandler) Status() (int, int) {
return b.bufSize, len(b.sinkCh)
} |
// Handle puts rec to the sink. | func (b *SinkHandler) Handle(rec *Record) {
select {
case b.sinkCh <- rec:
default:
fmt.Fprintf(os.Stderr, "SinkHandler buffer too small dropping record\n")
}
} |
//OnEvent calls lf with ctx and event. | func (lf ListenerFunc) OnEvent(ctx context.Context, event Event) {
lf(ctx, event)
} |
// NewRequest tries to make a request to the URL, returning the http.Response if it was successful, or an error if there was a problem.
// Optional Option arguments can be passed to specify contextual behaviour for this request. See MaxElapsedTime. | func NewRequest(url string, options ...Option) (*http.Response, error) {
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
request.Header.Add("Accept", "application/json")
request.Header.Add("User-Agent", "Performance-Platform-Client/1.0")
requestOptions := RequestOptions{MaxE... |
// MaxElapsedTime specifies the maximum duration that we should use to retry requests to the origin server. The default value is 5 seconds. | func MaxElapsedTime(duration time.Duration) Option {
return func(req *http.Request, ro *RequestOptions) Option {
previous := ro.MaxElapsedTime
ro.MaxElapsedTime = duration
return MaxElapsedTime(previous)
}
} |
// BearerToken sets the Authorization header for a request | func BearerToken(bearerToken string) Option {
return func(req *http.Request, ro *RequestOptions) Option {
previous := req.Header.Get("Authorization")
if bearerToken != "" {
req.Header.Add("Authorization", "Bearer "+bearerToken)
} else {
req.Header.Del("Authorization")
}
return BearerToken(previous)
}
... |
// ReadResponseBody reads the response body stream and returns a byte array, or an error if there was a problem. | func ReadResponseBody(response *http.Response) ([]byte, error) {
defer response.Body.Close()
return ioutil.ReadAll(response.Body)
} |
// Mark marks the begin/end of a function, and also indents the log output
// accordingly | func Mark(format string, args ...interface{}) func() {
if !debug {
return func() {}
}
Trace("START "+format, args...)
old := logger.Prefix()
logger.SetPrefix(old + "| ")
return func() {
logger.SetPrefix(old)
Trace("END "+format, args...)
}
} |
// RoundTrip parses incoming GET "HTTP" request and transforms it into
// commands to ftp client | func (rt *FTPRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
if request.URL.Scheme != "ftp" {
return nil, fmt.Errorf("only ftp protocol is supported, got %s", request.Proto)
}
if request.Method != "GET" {
return nil, fmt.Errorf("only GET method is supported, got %s", request.Method)
}
... |
// LexRun starts lexing using Lexer l, and a context Lexer ctx. "Context" in
// this case can be thought as the concret lexer, and l is the parent class.
// This is a utility function to be called from concrete Lexer types | func LexRun(l Lexer) {
for fn := l.GetEntryPoint(); fn != nil; {
fn = fn(l)
}
close(l.Items())
} |
// This method moves the cursor 1 rune if the rune is contained in the given
// string. This is a utility function to be called from concrete Lexer types | func AcceptAny(l Lexer, valid string) bool {
if strings.IndexRune(valid, l.Next()) >= 0 {
return true
}
l.Backup()
return false
} |
// AcceptRun takes a string, and moves the cursor forward as long as
// the input matches one of the given runes in the string
// This is a utility function to be called from concrete Lexer types | func AcceptRun(l Lexer, valid string) bool {
guard := Mark("lex.AcceptRun %q", valid)
defer guard()
return AcceptRunFunc(l, func(r rune) bool {
return strings.IndexRune(valid, r) >= 0
})
} |
// AcceptString returns true if the given string can be matched exactly.
// This is a utility function to be called from concrete Lexer types | func AcceptString(l Lexer, word string, rewind bool) (ok bool) {
i := 0
defer func() {
if rewind {
Trace("Rewinding AccepString(%q) (%d runes)\n", word, i)
for j := i; j > 0; j-- {
l.Backup()
}
}
Trace("AcceptString returning %s\n", ok)
}()
for pos := 0; pos < len(word); {
r, width := utf8.Dec... |
// NewMetaClient returns a new MetaClient implementation with sensible defaults. | func NewMetaClient(baseURL string, log *logrus.Logger) MetaClient {
return &defaultMetaClient{baseURL, log}
} |
//Handle calls hf with ctx and command. | func (hf HandlerFunc) Handle(ctx context.Context, command Command) (result interface{}, err error) {
return hf(ctx, command)
} |
//Handle associates a Handler in b that will be called when a Command whose type
//equals command's type.
//Only one Handler is allowed per Command type. Any previously added Handlers
//with the same commandType will be overwritten.
//prev is the Handler previously associated with commandType if it exists. | func (b *Bus) Handle(command Command, handler Handler) (prev Handler) {
b.lock.Lock()
defer b.lock.Unlock()
return b.putHandler(reflect.TypeOf(command), handler)
} |
//Listen registers lis to be called for all Commands at the time in the
//Command lifecycle denoted by et.
//A value for et that is not documented in this package will never be called. | func (b *Bus) Listen(et EventType, lis Listener) {
b.lock.Lock()
defer b.lock.Unlock()
b.appendListener(et, nil, lis)
} |
//ListenCommand registers lis to be called for Commands of the same type as command
//at the time in the Command lifecycle denoted by et.
//A value for et that is not documented in this package will never be called. | func (b *Bus) ListenCommand(et EventType, command Command, lis Listener) {
b.lock.Lock()
defer b.lock.Unlock()
b.appendListener(et, command, lis)
} |
//RemoveHandler removes the Handler associated with Command's type and returns it.
//This is a no-op and returns nil if a Handler does not exist for command. | func (b *Bus) RemoveHandler(command Command) Handler {
b.lock.Lock()
defer b.lock.Unlock()
commandType := reflect.TypeOf(command)
handler := b.handlers[commandType]
delete(b.handlers, commandType)
return handler
} |
//RemoveListener removes all Listeners that match lis (via ==) and et.
//The return value indicates if any Listeners were removed. | func (b *Bus) RemoveListener(et EventType, lis Listener) bool {
b.lock.Lock()
defer b.lock.Unlock()
removed := b.removeListeners(
et,
func(_ Command, _lis Listener) bool {
return _lis == lis
},
)
return len(removed) > 0
} |
//RemoveListenerCommand remove all Listeners that were registered with Command type
//equal to command's and et.
//It returns all removed Listeners. | func (b *Bus) RemoveListenerCommand(et EventType, command Command) []Listener {
b.lock.Lock()
defer b.lock.Unlock()
return b.removeListeners(
et,
func(_command Command, _ Listener) bool {
return reflect.TypeOf(_command) == reflect.TypeOf(command)
},
)
} |
//Execute is sugar for b.ExecuteContext(context.Background(), command). | func (b *Bus) Execute(command Command) (result interface{}, err error) {
return b.ExecuteContext(context.Background(), command)
} |
//ExecuteContext attempts to find a Handler for command's Type().
//If a Handler is not found, then ErrHandlerNotFound is returned immediately.
//If a Handler is found, then a new goroutine is spawned and all registered Before
//Listeners are called, followed by command's Handler, finally followed by all
//registered A... | func (b *Bus) ExecuteContext(ctx context.Context, command Command) (result interface{}, err error) {
b.lock.RLock()
defer b.lock.RUnlock()
handler, ok := b.handlers[reflect.TypeOf(command)]
if !ok {
return nil, &HandlerNotFoundError{command}
}
return b.execute(ctx, command, handler)
} |
// Calculate the pagination metadata for the next page of the result set.
// Takes the metadata used to request the current page so that it can use the
// same sort/orderby options | func (p *PaginationResponseMeta) nextPage(originalQuery *PaginationMeta) (next *PaginationMeta) {
nextOffset := p.Offset + p.Length
if nextOffset >= p.Found {
return nil
}
next = &PaginationMeta{}
next.Offset = nextOffset
next.Length = p.Length
if originalQuery != nil {
next.OrderBy = originalQuery.OrderB... |
// EncodeValues is implemented to allow other strucs to embed PaginationMeta and
// still use github.com/google/go-querystring/query to encode the struct. It
// makes PaginationMeta implement query.Encoder. | func (m *PaginationMeta) EncodeValues(name string, values *url.Values) error {
if m == nil {
return nil
}
if m.Offset != 0 {
values.Set("offset", fmt.Sprintf("%d", m.Offset))
}
if m.Length != 0 {
values.Set("length", fmt.Sprintf("%d", m.Length))
}
if m.OrderBy != "" {
values.Set("orderby", m.OrderBy)
}... |
//
// Client
// NewCachedClient creates a new fantasy client that checks and updates the
// given Cache when retrieving fantasy content.
//
// See NewLRUCache | func NewCachedClient(cache Cache, client HTTPClient) *Client {
return &Client{
Provider: &cachedContentProvider{
delegate: NewClient(client).Provider,
cache: cache,
},
}
} |
// NewClient creates a Client that to communicate with the Yahoo fantasy
// sports API. See the package level documentation for one way to create a
// http.Client that can authenticate with Yahoo's APIs which can be passed
// in here. | func NewClient(c HTTPClient) *Client {
return &Client{
Provider: &xmlContentProvider{
client: &countingHTTPApiClient{
client: c,
requestCount: 0,
},
},
}
} |
// GetConsumer generates an OAuth Consumer for the Yahoo fantasy sports API | func GetConsumer(clientID string, clientSecret string) *oauth.Consumer {
return oauth.NewConsumer(
clientID,
clientSecret,
oauth.ServiceProvider{
RequestTokenUrl: YahooRequestTokenURL,
AuthorizeTokenUrl: YahooAuthTokenURL,
AccessTokenUrl: YahooGetTokenURL,
})
} |
// GetOAuth2Config generates an OAuth 2 configuration for the Yahoo fantasy
// sports API | func GetOAuth2Config(clientID string, clientSecret string, redirectURL string) *oauth2.Config {
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"fspt-r"},
Endpoint: oauth2.Endpoint{
AuthURL: YahooOauth2AuthURL,
TokenURL: Yaho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.