...

Source file src/edge-infra.dev/pkg/lib/server/options.go

Documentation: edge-infra.dev/pkg/lib/server

     1  package server
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"os"
     7  
     8  	"github.com/gin-gonic/gin"
     9  )
    10  
    11  // Option functions set unexported private fields in the ServerConfig.
    12  // Use it to set things like the storage backend and port.
    13  type Option func(*Config) error
    14  
    15  func validPortNumber(port int) error {
    16  	if port <= 0 || port > 65535 {
    17  		return fmt.Errorf("Invalid port number %q", port)
    18  	}
    19  	return nil
    20  }
    21  
    22  // OptionPort sets the port to listen on. Omitting the ServerOptionPort causes the server to use port 80.
    23  func OptionPort(port int) Option {
    24  	return func(cfg *Config) error {
    25  		cfg.port = port
    26  		return validPortNumber(port)
    27  	}
    28  }
    29  
    30  // OptionHandler serves the gin handler on the provided path.
    31  func OptionHandler(path string, handler gin.HandlerFunc) Option {
    32  	return func(c *Config) error {
    33  		if handler == nil || path == "" {
    34  			return fmt.Errorf("handler and path must be set")
    35  		}
    36  		if c.handlers == nil {
    37  			c.handlers = make(map[string]Handler)
    38  		}
    39  		if _, taken := c.handlers[path]; taken {
    40  			return fmt.Errorf("handler path %q already registered", path)
    41  		}
    42  		c.handlers[path] = Handler(handler)
    43  		return nil
    44  	}
    45  }
    46  
    47  // OptionSecure creates an https server using the provided tls cert and key files.
    48  //
    49  // If the OptionPort is not set, then the `:https` Addr is used.
    50  func OptionSecure(certFile, keyFile string) Option {
    51  	return func(cfg *Config) error {
    52  		var f, err = os.Open(certFile)
    53  		if err != nil {
    54  			return fmt.Errorf("could not open cert file %q because of error: %w", certFile, err)
    55  		}
    56  		f.Close()
    57  		f, err = os.Open(keyFile)
    58  		if err != nil {
    59  			return fmt.Errorf("could not open key file %q because of error: %w", keyFile, err)
    60  		}
    61  		f.Close()
    62  
    63  		cfg.secure = true
    64  		cfg.secureCertFile = certFile
    65  		cfg.secureKeyFile = keyFile
    66  		return nil
    67  	}
    68  }
    69  
    70  // OptionListener is used to set a custom net.Listener for the server.
    71  // This server option is used in tests because some CICD environments don't allow ports to be opened.
    72  func OptionListener(l net.Listener) Option {
    73  	return func(cfg *Config) error {
    74  		cfg.listener = l
    75  		return nil
    76  	}
    77  }
    78  

View as plain text