本文整理汇总了Golang中strings.HasPrefix函数的典型用法代码示例。如果您正苦于以下问题:Golang HasPrefix函数的具体用法?Golang HasPrefix怎么用?Golang HasPrefix使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了HasPrefix函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: urlShortenerMain
func urlShortenerMain(client *http.Client, argv []string) {
if len(argv) != 1 {
fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx (to look up details)\n")
fmt.Fprintf(os.Stderr, " urlshortener http://example.com/long (to shorten)\n")
return
}
svc, _ := urlshortener.New(client)
urlstr := argv[0]
// short -> long
if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
url, err := svc.Url.Get(urlstr).Do()
if err != nil {
log.Fatalf("URL Get: %v", err)
}
fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
return
}
// long -> short
url, err := svc.Url.Insert(&urlshortener.Url{
Kind: "urlshortener#url", // Not really needed
LongUrl: urlstr,
}).Do()
if err != nil {
log.Fatalf("URL Insert: %v", err)
}
fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
示例2: Report
// When a test is skipped or fails, runtime.Goexit() is called which destroys the callstack.
// This means the name of the test case is lost, so we need to grab a copy of pc before.
func Report(t testing.TB) {
// If the goroutine panics, Fatal()s, or Skip()s, the function name is at the 3rd callstack
// layer. On success, its at 1st. Since it's hard to check which happened, just try both.
pcs := make([]uintptr, 10)
total := runtime.Callers(1, pcs)
var name string
for _, pc := range pcs[:total] {
fn := runtime.FuncForPC(pc)
fullName := fn.Name()
if strings.HasPrefix(path.Ext(fullName), ".Test") {
// Skip the leading .
name = string([]byte(path.Ext(fullName))[1:])
break
}
}
if name == "" {
return
}
allCaseInfos.lock.Lock()
defer allCaseInfos.lock.Unlock()
allCaseInfos.Cases = append(allCaseInfos.Cases, &caseInfo{
Name: name,
Passed: !t.Failed() && !t.Skipped(),
Skipped: t.Skipped(),
Fatal: t.Failed() && !strings.HasPrefix(name, "TestSoon"),
})
}
示例3: setScreen
//export setScreen
func setScreen(scale int) {
C.uname(&C.sysInfo)
name := C.GoString(&C.sysInfo.machine[0])
var v float32
switch {
case strings.HasPrefix(name, "iPhone"):
v = 163
case strings.HasPrefix(name, "iPad"):
// TODO: is there a better way to distinguish the iPad Mini?
switch name {
case "iPad2,5", "iPad2,6", "iPad2,7", "iPad4,4", "iPad4,5", "iPad4,6", "iPad4,7":
v = 163 // iPad Mini
default:
v = 132
}
default:
v = 163 // names like i386 and x86_64 are the simulator
}
if v == 0 {
log.Printf("unknown machine: %s", name)
v = 163 // emergency fallback
}
pixelsPerPt = v * float32(scale) / 72
screenScale = scale
}
示例4: checkSourceURI
// checkSourceURI performs a check on the URI associated with the build
// to make sure that it is live before proceeding with the build.
func (d *DockerBuilder) checkSourceURI() error {
rawurl := d.build.Spec.Source.Git.URI
if !d.git.ValidCloneSpec(rawurl) {
return fmt.Errorf("Invalid git source url: %s", rawurl)
}
if strings.HasPrefix(rawurl, "git://") || strings.HasPrefix(rawurl, "[email protected]") {
return nil
}
if !strings.HasPrefix(rawurl, "http://") && !strings.HasPrefix(rawurl, "https://") {
rawurl = fmt.Sprintf("https://%s", rawurl)
}
srcURL, err := url.Parse(rawurl)
if err != nil {
return err
}
host := srcURL.Host
if strings.Index(host, ":") == -1 {
switch srcURL.Scheme {
case "http":
host += ":80"
case "https":
host += ":443"
}
}
dialer := net.Dialer{Timeout: d.urlTimeout}
conn, err := dialer.Dial("tcp", host)
if err != nil {
return err
}
return conn.Close()
}
示例5: initApp
func (app *AppPlugin) initApp() {
app.initFrontendPlugin()
// check if we have child panels
for _, panel := range Panels {
if strings.HasPrefix(panel.PluginDir, app.PluginDir) {
panel.setPathsBasedOnApp(app)
app.FoundChildPlugins = append(app.FoundChildPlugins, &PluginInclude{
Name: panel.Name,
Id: panel.Id,
Type: panel.Type,
})
}
}
// check if we have child datasources
for _, ds := range DataSources {
if strings.HasPrefix(ds.PluginDir, app.PluginDir) {
ds.setPathsBasedOnApp(app)
app.FoundChildPlugins = append(app.FoundChildPlugins, &PluginInclude{
Name: ds.Name,
Id: ds.Id,
Type: ds.Type,
})
}
}
// slugify pages
for _, page := range app.Pages {
if page.Slug == "" {
page.Slug = slug.Make(page.Name)
}
}
}
示例6: importAccounts
func (g *gajimImporter) importAccounts(f string) (map[string]gajimAccountInfo, bool) {
file, err := os.Open(f)
if err != nil {
return nil, false
}
defer file.Close()
sc := bufio.NewScanner(file)
accountSettings := make(map[string]map[string]string)
proxies := make(map[string]map[string]string)
for sc.Scan() {
val := sc.Text()
ln := strings.SplitN(val, " = ", 2)
if len(ln) == 2 {
key := ln[0]
switch {
case strings.HasPrefix(key, "accounts."):
addNamedValue(accountSettings, ln, "accounts.")
case strings.HasPrefix(key, "proxies."):
addNamedValue(proxies, ln, "proxies.")
}
}
}
accountInfo := make(map[string]gajimAccountInfo)
for k, v := range accountSettings {
accountInfo[k] = transformSettingsIntoAccount(k, v, proxies)
}
return accountInfo, true
}
示例7: AddColumn
func (self *Table) AddColumn(name string, columnType string, defval sqltypes.Value, extra string, isPk, nullable bool) {
index := len(self.Columns)
self.Columns = append(self.Columns, TableColumn{Name: name})
self.Columns[index].IsPk = isPk
self.Columns[index].Nullable = nullable
if strings.Contains(columnType, "int") {
self.Columns[index].Category = CAT_NUMBER
} else if strings.HasPrefix(columnType, "varbinary") {
self.Columns[index].Category = CAT_VARBINARY
} else if strings.HasPrefix(columnType, "fractional") {
self.Columns[index].Category = CAT_FRACTIONAL
} else {
self.Columns[index].Category = CAT_OTHER
}
if extra == "auto_increment" {
self.Columns[index].IsAuto = true
self.Columns[index].NextId = 0
// Ignore default value, if any
return
} else if extra == "uuid" {
self.Columns[index].IsUUID = true
}
if defval.IsNull() {
return
}
if self.Columns[index].Category == CAT_NUMBER {
self.Columns[index].Default = sqltypes.MakeNumeric(defval.Raw())
} else {
self.Columns[index].Default = sqltypes.MakeString(defval.Raw())
}
}
示例8: registerCollectors
func (m *manager) registerCollectors(collectorConfigs map[string]string, cont *containerData) error {
for k, v := range collectorConfigs {
configFile, err := cont.ReadFile(v, m.inHostNamespace)
if err != nil {
return fmt.Errorf("failed to read config file %q for config %q, container %q: %v", k, v, cont.info.Name, err)
}
glog.V(3).Infof("Got config from %q: %q", v, configFile)
if strings.HasPrefix(k, "prometheus") || strings.HasPrefix(k, "Prometheus") {
newCollector, err := collector.NewPrometheusCollector(k, configFile)
if err != nil {
glog.Infof("failed to create collector for container %q, config %q: %v", cont.info.Name, k, err)
return err
}
err = cont.collectorManager.RegisterCollector(newCollector)
if err != nil {
glog.Infof("failed to register collector for container %q, config %q: %v", cont.info.Name, k, err)
return err
}
} else {
newCollector, err := collector.NewCollector(k, configFile)
if err != nil {
glog.Infof("failed to create collector for container %q, config %q: %v", cont.info.Name, k, err)
return err
}
err = cont.collectorManager.RegisterCollector(newCollector)
if err != nil {
glog.Infof("failed to register collector for container %q, config %q: %v", cont.info.Name, k, err)
return err
}
}
}
return nil
}
示例9: enable
func enable(c *cli.Context) {
changed := false
cfg, err := config.LoadConfig()
if err != nil {
log.Fatal(err)
}
for _, service := range c.Args() {
if val, ok := cfg.Rancher.ServicesInclude[service]; !ok || !val {
if strings.HasPrefix(service, "/") && !strings.HasPrefix(service, "/var/lib/rancher/conf") {
log.Fatalf("ERROR: Service should be in path /var/lib/rancher/conf")
}
if _, err := compose.LoadServiceResource(service, true, cfg); err != nil {
log.Fatalf("could not load service %s", service)
}
cfg.Rancher.ServicesInclude[service] = true
changed = true
}
}
if changed {
if err := cfg.Set("rancher.services_include", cfg.Rancher.ServicesInclude); err != nil {
log.Fatal(err)
}
}
}
示例10: handleErr
func (vtc *VtConn) handleErr(err error) (int, error) {
now := time.Now()
if vtc.timeFailed.IsZero() {
vtc.timeFailed = now
} else if now.Sub(vtc.timeFailed) > vtc.recoveryTimeout() {
vtc.Close()
return ErrTypeFatal, fmt.Errorf("vt: max recovery time exceeded: %v", err)
}
errType := ErrTypeApp
if tabletErr, ok := err.(TabletError); ok {
msg := strings.ToLower(tabletErr.err.Error())
if strings.HasPrefix(msg, "fatal") {
errType = ErrTypeFatal
} else if strings.HasPrefix(msg, "retry") {
errType = ErrTypeRetry
}
} else if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
errType = ErrTypeRetry
}
if errType == ErrTypeRetry && vtc.TransactionId != 0 {
errType = ErrTypeApp
err = fmt.Errorf("vt: cannot retry within a transaction: %v", err)
time.Sleep(vtc.reconnectDelay)
vtc.Close()
dialErr := vtc.dial()
log.Warningf("vt: redial error %v", dialErr)
}
return errType, err
}
示例11: stripFlags
func stripFlags(args []string) []string {
if len(args) < 1 {
return args
}
commands := []string{}
inQuote := false
for _, y := range args {
if !inQuote {
switch {
case strings.HasPrefix(y, "\""):
inQuote = true
case strings.Contains(y, "=\""):
inQuote = true
case !strings.HasPrefix(y, "-"):
commands = append(commands, y)
}
}
if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {
inQuote = false
}
}
return commands
}
示例12: URLsFromText
// URLsFromText extracts URLs from the email text bodies
func URLsFromText(con *data.Context, em *Email) ([]string, error) {
if em == nil {
return nil, nil
}
for _, t := range em.Texts {
if strings.HasPrefix(t.ContentType, contentTypeHTML) {
u, err := parseHTMLBody(con, t.Body)
if err != nil {
con.Log.Debugf("URLsFromText error while parsing HTML", err)
continue
}
return u, nil
}
if strings.HasPrefix(t.ContentType, contentTypeText) {
u, err := parseTextBody(con, t.Body)
if err != nil {
con.Log.Debugf("URLsFromText error while parsing Text", err)
continue
}
return u, nil
}
}
return nil, fmt.Errorf("Could not find an URL in the body.")
}
示例13: darwinFuseCheckVersion
func darwinFuseCheckVersion(node *core.IpfsNode) error {
// on OSX, check FUSE version.
if runtime.GOOS != "darwin" {
return nil
}
ov, errGFV := tryGFV()
if errGFV != nil {
// if we failed AND the user has told us to ignore the check we
// continue. this is in case fuse-version breaks or the user cannot
// install it, but is sure their fuse version will work.
if skip, err := userAskedToSkipFuseCheck(node); err != nil {
return err
} else if skip {
return nil // user told us not to check version... ok....
} else {
return errGFV
}
}
log.Debug("mount: osxfuse version:", ov)
if strings.HasPrefix(ov, "2.7.") || strings.HasPrefix(ov, "2.8.") {
return nil
}
return fmt.Errorf(errStrUpgradeFuse, ov)
}
示例14: EnvListForEndpoint
func (conf *Config) EnvListForEndpoint(dockerEndpoint, poolName string) ([]string, error) {
tsuruEndpoint, _ := config.GetString("host")
if !strings.HasPrefix(tsuruEndpoint, "http://") && !strings.HasPrefix(tsuruEndpoint, "https://") {
tsuruEndpoint = "http://" + tsuruEndpoint
}
tsuruEndpoint = strings.TrimRight(tsuruEndpoint, "/") + "/"
endpoint := dockerEndpoint
socket, _ := config.GetString("docker:bs:socket")
if socket != "" {
endpoint = "unix:///var/run/docker.sock"
}
token, err := conf.getToken()
if err != nil {
return nil, err
}
envList := []string{
"DOCKER_ENDPOINT=" + endpoint,
"TSURU_ENDPOINT=" + tsuruEndpoint,
"TSURU_TOKEN=" + token,
"SYSLOG_LISTEN_ADDRESS=udp://0.0.0.0:" + strconv.Itoa(container.BsSysLogPort()),
}
envMap := EnvMap{}
poolEnvMap := PoolEnvMap{}
err = conf.UpdateEnvMaps(envMap, poolEnvMap)
if err != nil {
return nil, err
}
for envName, envValue := range envMap {
envList = append(envList, fmt.Sprintf("%s=%s", envName, envValue))
}
for envName, envValue := range poolEnvMap[poolName] {
envList = append(envList, fmt.Sprintf("%s=%s", envName, envValue))
}
return envList, nil
}
示例15: ServeHTTP
// ServeHTTP implements the httpserver.Handler interface and serves requests,
// setting headers on the response according to the configured rules.
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
replacer := httpserver.NewReplacer(r, nil, "")
rww := &responseWriterWrapper{w: w}
for _, rule := range h.Rules {
if httpserver.Path(r.URL.Path).Matches(rule.Path) {
for name := range rule.Headers {
// One can either delete a header, add multiple values to a header, or simply
// set a header.
if strings.HasPrefix(name, "-") {
rww.delHeader(strings.TrimLeft(name, "-"))
} else if strings.HasPrefix(name, "+") {
for _, value := range rule.Headers[name] {
rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
}
} else {
for _, value := range rule.Headers[name] {
rww.Header().Set(name, replacer.Replace(value))
}
}
}
}
}
return h.Next.ServeHTTP(rww, r)
}