Skip to content

Commit

Permalink
Adds TLS support
Browse files Browse the repository at this point in the history
  • Loading branch information
rvflash committed Mar 27, 2019
1 parent a87c194 commit 2c5a8d5
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tcp

import (
"context"
"crypto/tls"
"net"
"sync"
"time"
Expand Down Expand Up @@ -120,13 +121,33 @@ func (s *Server) Use(f ...HandlerFunc) Router {
return s
}

const network = "tcp"

// Run starts listening on TCP address.
// This method will block the calling goroutine indefinitely unless an error happens.
func (s *Server) Run(addr string) (err error) {
l, err := net.Listen("tcp", addr)
l, err := net.Listen(network, addr)
if err != nil {
return
}
return s.serve(l)
}

// RunTLS acts identically to the Run method, except that it uses the TLS protocol.
// This method will block the calling goroutine indefinitely unless an error happens.
func (s *Server) RunTLS(addr, certFile, keyFile string) (err error) {
c, err := tlsConfig(certFile, keyFile)
if err != nil {
return
}
l, err := tls.Listen(network, addr, c)
if err != nil {
return
}
return s.serve(l)
}

func (s *Server) serve(l net.Listener) (err error) {
defer func() {
if err == nil {
err = l.Close()
Expand Down Expand Up @@ -177,6 +198,13 @@ func (s *Server) computeHandlers(segment string) []HandlerFunc {
return m
}

func tlsConfig(certFile, keyFile string) (*tls.Config, error) {
var err error
c := make([]tls.Certificate, 1)
c[0], err = tls.LoadX509KeyPair(certFile, keyFile)
return &tls.Config{Certificates: c}, err
}

func read(l net.Listener, to time.Duration) (net.Conn, error) {
c, err := l.Accept()
if err != nil {
Expand Down

0 comments on commit 2c5a8d5

Please sign in to comment.