How to split a string and assign it to variables
Two steps, for example,
package main
import (
"fmt"
"strings"
)
func main() {
s := strings.Split("127.0.0.1:5432", ":")
ip, port := s[0], s[1]
fmt.Println(ip, port)
}
Output:
127.0.0.1 5432
One step, for example,
package main
import (
"fmt"
"net"
)
func main() {
host, port, err := net.SplitHostPort("127.0.0.1:5432")
fmt.Println(host, port, err)
}
Output:
127.0.0.1 5432 <nil>
Since go
is flexible an you can create your own python
style split ...
package main
import (
"fmt"
"strings"
"errors"
)
type PyString string
func main() {
var py PyString
py = "127.0.0.1:5432"
ip, port , err := py.Split(":") // Python Style
fmt.Println(ip, port, err)
}
func (py PyString) Split(str string) ( string, string , error ) {
s := strings.Split(string(py), str)
if len(s) < 2 {
return "" , "", errors.New("Minimum match not found")
}
return s[0] , s[1] , nil
}
package main
import (
"fmt"
"strings"
)
func main() {
strs := strings.Split("127.0.0.1:5432", ":")
ip := strs[0]
port := strs[1]
fmt.Println(ip, port)
}
Here is the definition for strings.Split
// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
//
// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.
//
// If sep is empty, Split splits after each UTF-8 sequence. If both s
// and sep are empty, Split returns an empty slice.
//
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
The IPv6 addresses for fields like RemoteAddr
from http.Request
are formatted as "[::1]:53343"
So net.SplitHostPort
works great:
package main
import (
"fmt"
"net"
)
func main() {
host1, port, err := net.SplitHostPort("127.0.0.1:5432")
fmt.Println(host1, port, err)
host2, port, err := net.SplitHostPort("[::1]:2345")
fmt.Println(host2, port, err)
host3, port, err := net.SplitHostPort("localhost:1234")
fmt.Println(host3, port, err)
}
Output is:
127.0.0.1 5432 <nil>
::1 2345 <nil>
localhost 1234 <nil>