本文整理汇总了Golang中strings.Split函数的典型用法代码示例。如果您正苦于以下问题:Golang Split函数的具体用法?Golang Split怎么用?Golang Split使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Split函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TextToCSV
// TextToCSV converts the specified text to an array of csv values
func TextToCSV(text string) [][]string {
lines := strings.Split(text, "\n")
collection := [][]string{}
// should we skip the header
hasHeader := false
if len(lines) > 1 {
// first row should be the header
hasHeader = true
}
// parse each line
for idx, line := range lines {
// ignore the first row
if hasHeader {
if idx == 0 {
continue
}
}
// get data from each line
parts := strings.Split(line, ",")
if len(parts) < minCSVRowLen {
// ignore lines that don't have enough columns
continue
}
collection = append(collection, parts)
}
return collection
}
示例2: SendEmail
func SendEmail(to, subject, title, body string) bool {
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", username, password, hp[0])
var content_type string
mailtype := "html"
if mailtype == "html" {
content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
} else {
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
}
// 登录之
body = strings.Replace(bodyTpl, "$body", body, 1)
body = strings.Replace(body, "$title", title, 1)
msg := []byte("To: " + to + "\r\nFrom: " + username + "<" + username + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
send_to := strings.Split(to, ";")
err := smtp.SendMail(host+":"+port, auth, username, send_to, msg)
if err != nil {
return false
}
return true
}
示例3: getSites
/*
returns a zero length list if no sites are found.
*/
func getSites(w http.ResponseWriter, r *http.Request) ([]siteQ, bool) {
var sites = make([]siteQ, 0)
for _, ns := range strings.Split(r.URL.Query().Get("sites"), ",") {
nss := strings.Split(ns, ".")
if len(nss) != 2 {
web.BadRequest(w, r, "invalid sites query.")
return sites, false
}
sites = append(sites, siteQ{networkID: nss[0], siteID: nss[1]})
}
for _, s := range sites {
err := db.QueryRow("select name FROM fits.site join fits.network using (networkpk) where siteid = $2 and networkid = $1", s.networkID, s.siteID).Scan(&s.name)
if err == sql.ErrNoRows {
web.NotFound(w, r, "invalid siteID and networkID combination: "+s.siteID+" "+s.networkID)
return sites, false
}
if err != nil {
web.ServiceUnavailable(w, r, err)
return sites, false
}
}
return sites, true
}
示例4: handlePTRQuery
func (r *resolver) handlePTRQuery(ptr string, query *dns.Msg) (*dns.Msg, error) {
parts := []string{}
if strings.HasSuffix(ptr, ptrIPv4domain) {
parts = strings.Split(ptr, ptrIPv4domain)
} else if strings.HasSuffix(ptr, ptrIPv6domain) {
parts = strings.Split(ptr, ptrIPv6domain)
} else {
return nil, fmt.Errorf("invalid PTR query, %v", ptr)
}
host := r.backend.ResolveIP(parts[0])
if len(host) == 0 {
return nil, nil
}
logrus.Debugf("Lookup for IP %s: name %s", parts[0], host)
fqdn := dns.Fqdn(host)
resp := new(dns.Msg)
resp.SetReply(query)
setCommonFlags(resp)
rr := new(dns.PTR)
rr.Hdr = dns.RR_Header{Name: ptr, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: respTTL}
rr.Ptr = fqdn
resp.Answer = append(resp.Answer, rr)
return resp, nil
}
示例5: format_reply_portfoliostocks
/*
* Function to format the reply of the PortFolio Stocks
* @params stocks: String which holds values like `GOOGL:0:$656.99,APPL:5:$96.11`
* @params stockdata: Stucture of the YAHOO API
* @return: Formatted string like 'GOOGL:0:+$656.99','APPL:5:+$96.11'
*/
func format_reply_portfoliostocks(stocks string, stockdata *StockData) string {
var value string
stock := strings.Split(stocks, ",")
for i := 0; i < len(stockdata.List.Resources); i++ {
StockName := stockdata.List.Resources[i].Resource.Fields.Symbol
for j := 0; j < len(stock); j++ {
if !strings.EqualFold(StockName, strings.Split(stock[j], ":")[0]) {
continue
}
CurrentMarketValue, _ := strconv.ParseFloat(stockdata.List.Resources[i].Resource.Fields.Price, 64)
StockPrice, _ := strconv.ParseFloat(strings.Split(stock[j], ":")[2], 64)
quantity := strings.Split(stock[j], ":")[1]
value = value + ",'" + StockName + ":" + quantity
if CurrentMarketValue > StockPrice {
value = value + ":+$"
} else if CurrentMarketValue < StockPrice {
value = value + ":-$"
} else {
value = value + ":$"
}
value = value + strconv.FormatFloat(CurrentMarketValue, 'f', 2, 64) + "'"
}
}
return strings.Trim(value, ",")
}
示例6: GetIP
func (d *Driver) GetIP() (string, error) {
// DHCP is used to get the IP, so virtualbox hosts don't have IPs unless
// they are running
s, err := d.GetState()
if err != nil {
return "", err
}
if s != state.Running {
return "", drivers.ErrHostIsNotRunning
}
output, err := drivers.RunSSHCommandFromDriver(d, "ip addr show dev eth1")
if err != nil {
return "", err
}
log.Debugf("SSH returned: %s\nEND SSH\n", output)
// parse to find: inet 192.168.59.103/24 brd 192.168.59.255 scope global eth1
lines := strings.Split(output, "\n")
for _, line := range lines {
vals := strings.Split(strings.TrimSpace(line), " ")
if len(vals) >= 2 && vals[0] == "inet" {
return vals[1][:strings.Index(vals[1], "/")], nil
}
}
return "", fmt.Errorf("No IP address found %s", output)
}
示例7: QueueRemoteWrite
// return true if data needs to be written here
func QueueRemoteWrite(req *gomemcached.MCRequest) {
key := req.Key
nodeList := getVbucketNode(int(findShard(string(key))))
nodes := strings.Split(nodeList, ";")
if len(nodes) < 1 {
log.Fatal("Nodelist is empty. Cannot proceed")
}
if len(nodes) < 2 {
//no replica
return
}
var remoteNode string
// figure out which is the remote host and queue to the write to that node
for _, node := range nodes {
found := false
hostname := strings.Split(node, ":")
for _, ip := range ipList {
if ip == hostname[0] {
found = true
continue
}
}
if found == false {
remoteNode = node
}
}
ri := &repItem{host: remoteNode, req: req, opcode: OP_REP}
repChan <- ri
return
}
示例8: decodeSecureCookie
func decodeSecureCookie(value string) (user string, session string, err os.Error) {
parts := strings.Split(value, "|", 3)
if len(parts) != 3 {
err = os.NewError("Malformed cookie value")
return
}
val := parts[0]
timestamp := parts[1]
sig := parts[2]
// Check signature
if getCookieSig([]byte(val), timestamp) != sig {
return "", "", os.NewError("Signature error, cookie is invalid")
}
// Check time stamp
ts, _ := strconv.Atoi64(timestamp)
if ts+maxAge < time.UTC().Seconds() {
return "", "", os.NewError("Cookie is outdated")
}
buf := bytes.NewBufferString(val)
encoder := base64.NewDecoder(base64.StdEncoding, buf)
res, _ := ioutil.ReadAll(encoder)
str := string(res)
lst := strings.Split(str, "!", -1)
if len(lst) != 2 {
return "", "", os.NewError("Missing !")
}
return lst[0], lst[1], nil
}
示例9: parseSwarm
// TODO: This could use a unit test.
func parseSwarm(hostURL string, h *host.Host) (string, error) {
swarmOptions := h.HostOptions.SwarmOptions
if !swarmOptions.Master {
return "", fmt.Errorf("%q is not a swarm master. The --swarm flag is intended for use with swarm masters", h.Name)
}
u, err := url.Parse(swarmOptions.Host)
if err != nil {
return "", fmt.Errorf("There was an error parsing the url: %s", err)
}
parts := strings.Split(u.Host, ":")
swarmPort := parts[1]
// get IP of machine to replace in case swarm host is 0.0.0.0
mURL, err := url.Parse(hostURL)
if err != nil {
return "", fmt.Errorf("There was an error parsing the url: %s", err)
}
mParts := strings.Split(mURL.Host, ":")
machineIP := mParts[0]
hostURL = fmt.Sprintf("tcp://%s:%s", machineIP, swarmPort)
return hostURL, nil
}
示例10: IsOwner
func IsOwner(req *gomemcached.MCRequest) bool {
key := req.Key
nodeList := getVbucketNode(int(findShard(string(key))))
nodes := strings.Split(nodeList, ";")
//log.Printf(" Nodes list %v key %s", nodes, string(key))
if strings.Contains(nodes[0], "localhost") || strings.Contains(nodes[0], "127.0.0.1") || nodes[0] == "" {
return true
}
if len(nodes) < 1 {
log.Fatal("Nodelist is empty. Cannot proceed")
}
for _, node := range nodes {
hostname := strings.Split(node, ":")
for _, ip := range ipList {
if ip == hostname[0] {
return true
}
}
}
return false
}
示例11: TestNewServiceLogfile
func (s *initSystemSuite) TestNewServiceLogfile(c *gc.C) {
s.conf.Logfile = "/var/log/juju/machine-0.log"
service := s.newService(c)
dirname := fmt.Sprintf("%s/init/%s", s.dataDir, s.name)
script := `
#!/usr/bin/env bash
# Set up logging.
touch '/var/log/juju/machine-0.log'
chown syslog:syslog '/var/log/juju/machine-0.log'
chmod 0600 '/var/log/juju/machine-0.log'
exec >> '/var/log/juju/machine-0.log'
exec 2>&1
# Run the script.
`[1:] + jujud + " machine-0"
c.Check(service, jc.DeepEquals, &systemd.Service{
Service: common.Service{
Name: s.name,
Conf: common.Conf{
Desc: s.conf.Desc,
ExecStart: dirname + "/exec-start.sh",
Logfile: "/var/log/juju/machine-0.log",
},
},
UnitName: s.name + ".service",
ConfName: s.name + ".service",
Dirname: dirname,
Script: []byte(script),
})
// This gives us a more readable output if they aren't equal.
c.Check(string(service.Script), gc.Equals, script)
c.Check(strings.Split(string(service.Script), "\n"), jc.DeepEquals, strings.Split(script, "\n"))
}
示例12: getUsernameAndPassword
func getUsernameAndPassword(r *libhttp.Request) (string, string, error) {
q := r.URL.Query()
username, password := q.Get("u"), q.Get("p")
if username != "" && password != "" {
return username, password, nil
}
auth := r.Header.Get("Authorization")
if auth == "" {
return "", "", nil
}
fields := strings.Split(auth, " ")
if len(fields) != 2 {
return "", "", fmt.Errorf("Bad auth header")
}
bs, err := base64.StdEncoding.DecodeString(fields[1])
if err != nil {
return "", "", fmt.Errorf("Bad encoding")
}
fields = strings.Split(string(bs), ":")
if len(fields) != 2 {
return "", "", fmt.Errorf("Bad auth value")
}
return fields[0], fields[1], nil
}
示例13: compareTo
func (me Version) compareTo(other Version) int {
var (
meTab = strings.Split(string(me), ".")
otherTab = strings.Split(string(other), ".")
)
max := len(meTab)
if len(otherTab) > max {
max = len(otherTab)
}
for i := 0; i < max; i++ {
var meInt, otherInt int
if len(meTab) > i {
meInt, _ = strconv.Atoi(meTab[i])
}
if len(otherTab) > i {
otherInt, _ = strconv.Atoi(otherTab[i])
}
if meInt > otherInt {
return 1
}
if otherInt > meInt {
return -1
}
}
return 0
}
示例14: parseINI
// parseINI takes the contents of a credentials file and returns a map, whose keys
// are the various profiles, and whose values are maps of the settings for the
// profiles
func parseINI(fileContents string) map[string]map[string]string {
profiles := make(map[string]map[string]string)
lines := strings.Split(fileContents, "\n")
var currentSection map[string]string
for _, line := range lines {
// remove comments, which start with a semi-colon
if split := strings.Split(line, ";"); len(split) > 1 {
line = split[0]
}
// check if the line is the start of a profile.
//
// for example:
// [default]
//
// otherwise, check for the proper setting
// property=value
if sectMatch := iniSectionRegexp.FindStringSubmatch(line); len(sectMatch) == 2 {
currentSection = make(map[string]string)
profiles[sectMatch[1]] = currentSection
} else if setMatch := iniSettingRegexp.FindStringSubmatch(line); len(setMatch) == 3 && currentSection != nil {
currentSection[setMatch[1]] = setMatch[2]
}
}
return profiles
}
示例15: ParseData
func (r *PerfResult) ParseData() map[string]map[string]*ParsedPerfResult {
if r.parsedData != nil {
return r.parsedData
}
res := make(map[string]map[string]*ParsedPerfResult)
for _, str := range r.Data {
ss := strings.Split(str, "|")
builder := ss[0]
bench := ss[1]
ok := ss[2]
m := res[builder]
if m == nil {
m = make(map[string]*ParsedPerfResult)
res[builder] = m
}
var p ParsedPerfResult
p.OK = ok == "ok"
p.Metrics = make(map[string]uint64)
p.Artifacts = make(map[string]string)
for _, entry := range ss[3:] {
if strings.HasPrefix(entry, "file:") {
ss1 := strings.Split(entry[len("file:"):], "=")
p.Artifacts[ss1[0]] = ss1[1]
} else {
ss1 := strings.Split(entry, "=")
val, _ := strconv.ParseUint(ss1[1], 10, 64)
p.Metrics[ss1[0]] = val
}
}
m[bench] = &p
}
r.parsedData = res
return res
}