Debian Codegraph @

hostport.go

raw
1 package utils
2
3 import (
4 "bytes"
5
6 "github.com/gofiber/utils/v2/internal/unsafeconv"
7 )
8
9 // SplitHostPort splits "host:port", "[host]:port", and their %zone forms
10 // with net.SplitHostPort's exact rules, reporting failure as ok == false
11 // instead of a *net.AddrError; it accepts byte slices as well as strings,
12 // and the parts alias hostport.
13 func SplitHostPort[S byteSeq](hostport S) (host, port S, ok bool) { //nolint:nonamedreturns // the two same-typed parts are only readable named
14 b := unsafeconv.Bytes(hostport)
15 // The port starts after the last colon.
16 i := bytes.LastIndexByte(b, ':')
17 if i < 0 {
18 return host, port, false
19 }
20 j, k, hostEnd := 0, 0, i
21 if hostport[0] == '[' {
22 // Expect the first ']' just before the last ':'.
23 end := bytes.IndexByte(b, ']')
24 if end < 0 || end+1 != i {
25 return host, port, false
26 }
27 j, k, hostEnd = 1, end+1, end // there can't be a '[' resp. ']' before these positions
28 } else if bytes.IndexByte(b[:i], ':') >= 0 {
29 return host, port, false
30 }
31 if bytes.IndexByte(b[j:], '[') >= 0 || bytes.IndexByte(b[k:], ']') >= 0 {
32 return host, port, false
33 }
34 return hostport[j:hostEnd], hostport[i+1:], true
35 }