go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/listener_options.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"crypto/tls"
    12  	"net"
    13  
    14  	"go.charczuk.com/sdk/proxyproto"
    15  )
    16  
    17  // ListenerOptions creates a listener based on options.
    18  type ListenerOptions struct {
    19  	Network       string
    20  	Addr          string
    21  	ProxyProtocol *proxyproto.Config
    22  	TLS           *tls.Config
    23  }
    24  
    25  // GetListener creates a listener.
    26  func (lc *ListenerOptions) GetListener() (net.Listener, error) {
    27  	if lc.Network == "" {
    28  		lc.Network = "tcp"
    29  	}
    30  	if lc.Addr == "" {
    31  		if lc.TLS != nil {
    32  			lc.Addr = ":https"
    33  		} else {
    34  			lc.Addr = ":http"
    35  		}
    36  	}
    37  	listener, err := net.Listen(lc.Network, lc.Addr)
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  	if lc.ProxyProtocol != nil {
    42  		listener = &proxyproto.Listener{
    43  			ProxyHeaderTimeout: lc.ProxyProtocol.ProxyHeaderTimeout,
    44  			Listener:           listener,
    45  		}
    46  	}
    47  	if lc.TLS != nil {
    48  		listener = tls.NewListener(listener, lc.TLS)
    49  	}
    50  	return listener, nil
    51  }