github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/srvcache/server.go (about)

     1  // Copyright (c) 2018-2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package srvcache
     6  
     7  import (
     8  	"fmt"
     9  	"net/url"
    10  )
    11  
    12  // BasicServer is a representation of a network server host and port, implements Server
    13  type BasicServer struct {
    14  	host   string
    15  	port   uint16
    16  	scheme string
    17  }
    18  
    19  // Host retrieves the host for the server
    20  func (s *BasicServer) Host() string { return s.host }
    21  
    22  // SetHost sets the host for the server
    23  func (s *BasicServer) SetHost(host string) { s.host = host }
    24  
    25  // Port retrieves the port for the server
    26  func (s *BasicServer) Port() uint16 { return s.port }
    27  
    28  // SetPort sets the port for the server
    29  func (s *BasicServer) SetPort(port int) { s.port = uint16(port) }
    30  
    31  // Scheme retrieves the url scheme
    32  func (s *BasicServer) Scheme() string { return s.scheme }
    33  
    34  // SetScheme sets the url scheme
    35  func (s *BasicServer) SetScheme(scheme string) { s.scheme = scheme }
    36  
    37  // HostPort is a string in hostname:port format
    38  func (s *BasicServer) HostPort() string {
    39  	return fmt.Sprintf("%s:%d", s.host, s.port)
    40  }
    41  
    42  // URL creates a correct url from the server if scheme is known
    43  func (s *BasicServer) URL() (u *url.URL, err error) {
    44  	if s.Scheme() == "" {
    45  		return u, fmt.Errorf("server %s:%d has no scheme, cannot make a URL", s.host, s.port)
    46  	}
    47  
    48  	ustring := fmt.Sprintf("%s://%s:%d", s.scheme, s.host, s.port)
    49  
    50  	u, err = url.Parse(ustring)
    51  	if err != nil {
    52  		return u, fmt.Errorf("could not parse %s: %s", ustring, err)
    53  	}
    54  
    55  	return u, err
    56  }
    57  
    58  // String is a string representation of the server in url format
    59  func (s *BasicServer) String() string {
    60  	if s.scheme == "" {
    61  		return fmt.Sprintf("%s:%d", s.host, s.port)
    62  	}
    63  
    64  	return fmt.Sprintf("%s://%s:%d", s.scheme, s.host, s.port)
    65  }