github.com/searKing/golang/go@v1.2.117/net/hostport_test.go (about)

     1  package net_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/searKing/golang/go/net"
     7  )
     8  
     9  func TestSplitHostPort(t *testing.T) {
    10  	table := []struct {
    11  		Hostport string
    12  		Ip       string
    13  		Port     string
    14  	}{
    15  		{
    16  			Hostport: `localhost`,
    17  			Ip:       "localhost",
    18  			Port:     "",
    19  		},
    20  		{
    21  			Hostport: `localhost:`,
    22  			Ip:       "localhost",
    23  			Port:     "",
    24  		},
    25  		{
    26  			Hostport: `localhost:80`,
    27  			Ip:       "localhost",
    28  			Port:     "80",
    29  		},
    30  		{
    31  			Hostport: `:80`,
    32  			Ip:       "",
    33  			Port:     "80",
    34  		},
    35  		{
    36  			Hostport: `:`,
    37  			Ip:       "",
    38  			Port:     "",
    39  		},
    40  		{
    41  			Hostport: ``,
    42  			Ip:       "",
    43  			Port:     "",
    44  		},
    45  		{
    46  			Hostport: `[::1]:80`,
    47  			Ip:       "::1",
    48  			Port:     "80",
    49  		},
    50  		{
    51  			Hostport: `[::1]`,
    52  			Ip:       "::1",
    53  			Port:     "",
    54  		},
    55  		{
    56  			Hostport: `[::1%lo0]:80`,
    57  			Ip:       "::1%lo0",
    58  			Port:     "80",
    59  		},
    60  		{
    61  			Hostport: `[::1%lo0]:`,
    62  			Ip:       "::1%lo0",
    63  			Port:     "",
    64  		},
    65  	}
    66  
    67  	for i, test := range table {
    68  		qIp, qPort, err := net.SplitHostPort(test.Hostport)
    69  		if err != nil {
    70  			t.Errorf("#%d. got err %s, want err nil", i, err)
    71  		}
    72  		if qIp != test.Ip || qPort != test.Port {
    73  			t.Errorf("#%d. got %q:%q, want %q:%q", i, qIp, qPort, test.Ip, test.Port)
    74  		}
    75  	}
    76  }
    77  
    78  func TestHostportOrDefault(t *testing.T) {
    79  	table := []struct {
    80  		Hostport, DefHostport, R string
    81  	}{
    82  		{
    83  			Hostport:    ``,
    84  			DefHostport: `127.0.0.1:443`,
    85  			R:           `127.0.0.1:443`,
    86  		},
    87  		{
    88  			Hostport:    `localhost`,
    89  			DefHostport: `127.0.0.1:443`,
    90  			R:           `localhost:443`,
    91  		},
    92  		{
    93  			Hostport:    `localhost:`,
    94  			DefHostport: `127.0.0.1:443`,
    95  			R:           `localhost:443`,
    96  		},
    97  		{
    98  			Hostport:    `localhost:80`,
    99  			DefHostport: `127.0.0.1:443`,
   100  			R:           `localhost:80`,
   101  		},
   102  		{
   103  			Hostport:    `:80`,
   104  			DefHostport: `127.0.0.1:443`,
   105  			R:           `127.0.0.1:80`,
   106  		},
   107  	}
   108  
   109  	for i, test := range table {
   110  		qr := net.HostportOrDefault(test.Hostport, test.DefHostport)
   111  		if qr != test.R {
   112  			t.Errorf("%d. got %q, want %q", i, qr, test.R)
   113  		}
   114  	}
   115  }