本文整理汇总了Golang中strings.Trim函数的典型用法代码示例。如果您正苦于以下问题:Golang Trim函数的具体用法?Golang Trim怎么用?Golang Trim使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Trim函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: xmlToSocketLogWriter
func xmlToSocketLogWriter(filename string, props []xmlProperty, enabled bool) (SocketLogWriter, bool) {
endpoint := ""
protocol := "udp"
for _, prop := range props {
switch prop.Name {
case "endpoint":
endpoint = strings.Trim(prop.Value, " \r\n")
case "protocol":
protocol = strings.Trim(prop.Value, " \r\n")
default:
fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename)
}
}
if len(endpoint) == 0 {
fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "endpoint", filename)
return nil, false
}
if !enabled {
return nil, true
}
return NewSocketLogWriter(protocol, endpoint), true
}
示例2: UnmarshalXML
func (p *Problem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
pp := struct {
Id string `xml:"id"`
Name string `xml:"name"`
Available string `xml:"available"`
ProblemTimeLimit string `xml:"problemtimelimit"`
ProblemMemoryLimit string `xml:"problemmemorylimit"`
Status Status `xml:"status"`
SolvedList []SolvedUser `xml:"solved_list>user"`
}{}
if err := d.DecodeElement(&pp, &start); err != nil {
return err
}
available, err := strconv.Atoi(strings.Trim(pp.Available, "\n"))
problemTimeLimit, err := strconv.Atoi(strings.Trim(pp.ProblemTimeLimit, "\n"))
problemMemoryLimit, err := strconv.Atoi(strings.Trim(pp.ProblemMemoryLimit, "\n"))
if err != nil {
return err
}
*p = Problem{
Id: strings.Trim(pp.Id, "\n"),
Name: strings.Trim(pp.Name, "\n"),
Available: available,
ProblemTimeLimit: problemTimeLimit,
ProblemMemoryLimit: problemMemoryLimit,
Status: pp.Status,
SolvedList: pp.SolvedList,
}
return nil
}
示例3: cleanRawValue
func cleanRawValue(s string) string {
s = strings.Trim(s, " \t\n\r")
if len(s) == 0 {
return ""
}
inString := false
escape := false
for i := 0; i < len(s); i++ {
c := s[i]
if escape {
escape = false
continue
}
if c == '"' {
inString = !inString
continue
}
if inString && c == '\\' {
escape = true
continue
}
if c == '#' && !inString {
return strings.Trim(s[0:i], " \t\n\r")
}
}
return s
}
示例4: Build
func (b *buildFile) Build(context io.Reader) (string, error) {
// FIXME: @creack "name" is a terrible variable name
name, err := ioutil.TempDir("", "docker-build")
if err != nil {
return "", err
}
if err := Untar(context, name); err != nil {
return "", err
}
defer os.RemoveAll(name)
b.context = name
filename := path.Join(name, "Dockerfile")
if _, err := os.Stat(filename); os.IsNotExist(err) {
return "", fmt.Errorf("Can't build a directory with no Dockerfile")
}
fileBytes, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
dockerfile := string(fileBytes)
dockerfile = lineContinuation.ReplaceAllString(dockerfile, "")
stepN := 0
for _, line := range strings.Split(dockerfile, "\n") {
line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
// Skip comments and empty line
if len(line) == 0 || line[0] == '#' {
continue
}
tmp := strings.SplitN(line, " ", 2)
if len(tmp) != 2 {
return "", fmt.Errorf("Invalid Dockerfile format")
}
instruction := strings.ToLower(strings.Trim(tmp[0], " "))
arguments := strings.Trim(tmp[1], " ")
method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
if !exists {
fmt.Fprintf(b.out, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
continue
}
stepN += 1
fmt.Fprintf(b.out, "Step %d : %s %s\n", stepN, strings.ToUpper(instruction), arguments)
ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
if ret != nil {
return "", ret.(error)
}
fmt.Fprintf(b.out, " ---> %v\n", utils.TruncateID(b.image))
}
if b.image != "" {
fmt.Fprintf(b.out, "Successfully built %s\n", utils.TruncateID(b.image))
if b.rm {
b.clearTmp(b.tmpContainers)
}
return b.image, nil
}
return "", fmt.Errorf("An error occurred during the build\n")
}
示例5: findRootDevicePath
func (p linux) findRootDevicePath() (string, error) {
mounts, err := p.diskManager.GetMountsSearcher().SearchMounts()
if err != nil {
return "", bosherr.WrapError(err, "Searching mounts")
}
for _, mount := range mounts {
if mount.MountPoint == "/" && strings.HasPrefix(mount.PartitionPath, "/dev/") {
p.logger.Debug(logTag, "Found root partition: `%s'", mount.PartitionPath)
stdout, _, _, err := p.cmdRunner.RunCommand("readlink", "-f", mount.PartitionPath)
if err != nil {
return "", bosherr.WrapError(err, "Shelling out to readlink")
}
rootPartition := strings.Trim(stdout, "\n")
p.logger.Debug(logTag, "Symlink is: `%s'", rootPartition)
validRootPartition := regexp.MustCompile(`^/dev/[a-z]+1$`)
if !validRootPartition.MatchString(rootPartition) {
return "", bosherr.Error("Root partition is not the first partition")
}
return strings.Trim(rootPartition, "1"), nil
}
}
return "", bosherr.Error("Getting root partition device")
}
示例6: serverVersion
// as per http://www.mssqltips.com/sqlservertip/2563/understanding-the-sql-server-select-version-command/
func serverVersion(db *sql.DB) (sqlVersion, sqlPartNumber, osVersion string, err error) {
var v string
if err = db.QueryRow("select @@version").Scan(&v); err != nil {
return "", "", "", err
}
a := strings.SplitN(v, "\n", -1)
if len(a) < 4 {
return "", "", "", errors.New("SQL Server version string must have at least 4 lines: " + v)
}
for i := range a {
a[i] = strings.Trim(a[i], " \t")
}
l1 := strings.SplitN(a[0], "-", -1)
if len(l1) != 2 {
return "", "", "", errors.New("SQL Server version first line must have - in it: " + v)
}
i := strings.Index(a[3], " on ")
if i < 0 {
return "", "", "", errors.New("SQL Server version fourth line must have 'on' in it: " + v)
}
sqlVersion = l1[0] + a[3][:i]
osVersion = a[3][i+4:]
sqlPartNumber = strings.Trim(l1[1], " ")
l12 := strings.SplitN(sqlPartNumber, " ", -1)
if len(l12) < 2 {
return "", "", "", errors.New("SQL Server version first line must have space after part number in it: " + v)
}
sqlPartNumber = l12[0]
return sqlVersion, sqlPartNumber, osVersion, nil
}
示例7: parsePortRange
func parsePortRange(ports string) (uint16, uint16, error) {
segments := strings.Split(ports, "-")
fromPortStr := ""
toPortStr := ""
if len(segments) == 1 {
fromPortStr = segments[0]
toPortStr = fromPortStr
} else if len(segments) == 2 {
fromPortStr = segments[0]
toPortStr = segments[1]
}
fromPort, err := strconv.Atoi(strings.Trim(fromPortStr, " "))
if err != nil {
return 0, 0, err
}
toPort, err := strconv.Atoi(strings.Trim(toPortStr, " "))
if err != nil {
return 0, 0, err
}
return uint16(fromPort), uint16(toPort), nil
}
示例8: InitWithReader
//initial the configure by .properties file.
func (f *Fcfg) InitWithReader(reader *bufio.Reader) error {
for {
//read one line
bys, err := ReadLine(reader, 10000, false)
if err != nil {
break
}
//
line := string(bys)
line = strings.Trim(line, " ")
if len(line) < 1 {
continue
}
ps := strings.Split(line, "#")
if len(ps) < 1 || len(ps[0]) < 1 {
continue
}
line = ps[0]
ps = strings.SplitN(line, "=", 2)
if len(ps) < 2 {
fmt.Println(os.Stderr, "found not value key:", ps[0])
continue
}
key := f.EnvReplace(strings.Trim(ps[0], " "))
val := f.EnvReplace(strings.Trim(ps[1], " "))
(*f)[key] = val
}
return nil
}
示例9: connectServer
//连接服务器
func connectServer() {
//接通
conn, err := net.Dial("tcp", "localhost:7777")
checkError(err)
fmt.Println("连接成功!\n")
//输入
inputReader := bufio.NewReader(os.Stdin)
fmt.Println("你是谁?")
name, _ := inputReader.ReadString('\n')
//
trimName := strings.Trim(name, "\r\n")
conn.Write([]byte(trimName + " 接入了\n "))
fmt.Println("我们来聊天吧!按quit退出")
for {
//读一行
input, _ := inputReader.ReadString('\n')
trimInput := strings.Trim(input, "\r\n")
//如果quit就退出
if trimInput == "quit" {
fmt.Println("再见")
conn.Write([]byte(trimName + " 退出了 "))
return
}
//写出来
_, err = conn.Write([]byte(trimName + " says: " + trimInput))
go doServerStuff(conn)
}
}
示例10: parseStatus
func (s systemctl) parseStatus(sData string, err error) (Status, error) {
var st Status
lines := strings.Split(sData, "\n")
if err != nil {
errString := err.Error()
idx := strings.LastIndex(errString, " ")
exitCode, _ := strconv.Atoi(errString[idx+1 : len(errString)])
// SystemD status is 3 when service is stopped or does not exists
if exitCode != 3 {
return st, err
}
for _, line := range lines {
line = strings.Trim(line, " ")
// When services does not exists then "Loaded" contains "not-found"
if strings.HasPrefix(line, "Loaded") && strings.Contains(line, "not-found") {
return st, err
}
}
}
for _, line := range lines {
line = strings.Trim(line, " ")
if strings.HasPrefix(line, "Active") {
st.Running = strings.Contains(line, "active (running)")
if !st.Running {
break
}
} else if strings.HasPrefix(line, "Main PID") {
pid := line[10:len(line)]
idx := strings.Index(pid, " ")
pid = pid[0:idx]
st.PID, _ = strconv.Atoi(pid)
}
}
return st, nil
}
示例11: angryprof
// https://www.hackerrank.com/challenges/angry-professor
func angryprof() {
t, reader := readFirstIntLine()
for i := 0; i < t; i++ {
// Read in N and K
line, _ := reader.ReadString('\n')
row := strings.Split(strings.Trim(line, "\n"), " ")
strconv.Atoi(row[0])
k, _ := strconv.Atoi(row[1])
// Read in the students
line, _ = reader.ReadString('\n')
var nArrived int
for _, s := range splitInt(strings.Trim(line, "\n")) {
if s <= 0 {
nArrived++
}
}
if nArrived >= k {
fmt.Println("NO")
} else {
fmt.Println("YES")
}
}
}
示例12: Chain
// Chain performs all the child derivations necessary to end up with the key
// described with BIP32 notations, eg. m/44'/0'/1'/0/3.
func (k *Key) Chain(chain string) (*Key, error) {
low := strings.ToLower(chain)
splits := strings.Split(low, "/")
m := strings.Trim(splits[0], " ")
if m == "m" {
if k.depth != 0 {
return nil, fmt.Errorf("Origin key isn't a master.")
}
if len(splits) == 1 {
return k, nil
}
splits = splits[1:]
}
key := k
for i, s := range splits {
t := strings.Trim(s, " ")
var harden uint32
end := t[len(t)-1]
if end == 'h' || end == '\'' {
harden = 0x80000000
t = t[:len(t)-1]
}
u, err := strconv.ParseUint(strings.Trim(t, " "), 10, 32)
if err != nil {
return nil, fmt.Errorf("Couldn't parse number at position %d (%s): %v",
i, t, err)
}
key, err = key.Child(uint32(u) + harden)
if err != nil {
return nil, fmt.Errorf("Couldn't derive child #%d (%s): %v", i, s, err)
}
}
return key, nil
}
示例13: addCertWithTx
func (d *pgDataStore) addCertWithTx(tx *pgx.Tx, c *router.Certificate) error {
c.Cert = strings.Trim(c.Cert, " \n")
c.Key = strings.Trim(c.Key, " \n")
if _, err := tls.X509KeyPair([]byte(c.Cert), []byte(c.Key)); err != nil {
return httphelper.JSONError{
Code: httphelper.ValidationErrorCode,
Message: "Certificate invalid: " + err.Error(),
}
}
tlsCertSHA256 := sha256.Sum256([]byte(c.Cert))
if err := tx.QueryRow("select_certificate_by_sha", tlsCertSHA256[:]).Scan(&c.ID, &c.CreatedAt, &c.UpdatedAt); err != nil {
if err := tx.QueryRow("insert_certificate", c.Cert, c.Key, tlsCertSHA256[:]).Scan(&c.ID, &c.CreatedAt, &c.UpdatedAt); err != nil {
return err
}
}
for _, rid := range c.Routes {
if _, err := tx.Exec("delete_route_certificate_by_route_id", rid); err != nil {
return err
}
if _, err := tx.Exec("insert_route_certificate", rid, c.ID); err != nil {
return err
}
}
return nil
}
示例14: InspectJson
func InspectJson(ins []string) (out []string) {
var re []string
for _, in := range ins {
if JsonPart != "" {
in = JsonPart + in
}
in = strings.Trim(strings.TrimSpace(in), " ,")
charopen := 0
charclose := 0
for i, r := range in {
c := string(r)
if c == "{" {
charopen += 1
} else if c == "}" {
charclose += 1
}
if charopen == charclose && (charclose != 0 && charopen != 0) {
if len(in) == i+1 {
JsonPart = ""
} else {
JsonPart = in[i+1:]
}
re = append(re, strings.Trim(strings.TrimSpace(in[:i+1]), " ,"))
break
}
if charopen != charclose || (charclose == 0 && charopen == 0) {
JsonPart = in
}
}
}
return re
}
示例15: SMSHandler
func SMSHandler(w http.ResponseWriter, r *http.Request) {
sms := r.URL.Query().Get("Body")
sms = strings.Trim(sms, "8575-2838")
if sms == "" {
log.Println("Blank body.")
SendSMS(w, r, "Please send a text with: \"Name\" \"[email protected]\"")
return
}
info := strings.Fields(sms)
name := strings.Join(info[:len(info)-1], " ")
email := info[len(info)-1]
name = strings.Trim(name, "\"")
if name == "" {
log.Println("Blank name.")
SendSMS(w, r, "Please send a text with: \"Name\" \"[email protected]\"")
return
}
email = strings.Trim(email, "\"")
address := fmt.Sprintf("%s <%s>", name, email)
_, err := mail.ParseAddress(address)
if err != nil {
SendSMS(w, r, "Please try again with a valid email address.")
return
}
signup := Signup{Name: name, Email: email, Raw: sms, Timestamp: time.Now()}
log.Println(signup)
c := mgoSession.DB("sms_signup").C("signups")
err = c.Insert(signup)
if err != nil {
log.Println(err.Error())
}
SendSMS(w, r, fmt.Sprintf("Thanks for signing up, %s!", info[0]))
}