server

package
v0.0.0-...-edcedff Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2020 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package server provides convenience methods to creates and starting HTTP or HTTPS server plus Let's Encrypt support.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingCert thrown when starting TLS server without valid certificate.
	ErrMissingCert = errors.New("missing https certificate")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	ReadTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	MaxHeaderBytes    int
	ShutdownTimeout   time.Duration
}

type Option

type Option func(h *Server)

Option is a function to configure Server.

func WithAddr

func WithAddr(host, port string) Option

WithAddr sets server address.

func WithAutoTLS

func WithAutoTLS(host, cacheDir string) Option

WithAutoTLS sets host and cacheDir for auto-TLS.

func WithCert

func WithCert(cert, key []byte) Option

WithCert sets the certificate and matching private key.

func WithCertFile

func WithCertFile(cert, key string) Option

WithCertFile sets the location of the certificate and matching private key files.

func WithConfig

func WithConfig(config Config) Option

WithConfig sets http server configuration.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server an HTTP(s) server.

func New

func New(handler http.Handler, opts ...Option) *Server

New creates a new Server.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown shutting down the HTTP(s) server.

func (*Server) Start

func (s *Server) Start() error

Start stars HTTP server.

Example
package main

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/foodarchive/truffls/pkg/server"
)

func main() {
	srv := server.New(
		mux(),
		server.WithAddr("", "9876"),
	)

	defer func() {
		if err := srv.Shutdown(); err != nil {
			log.Fatal(err)
		}
	}()

	go func() {
		if err := srv.Start(); err != nil {
			log.Fatal(err)
		}
	}()

	time.Sleep(10 * time.Millisecond)

	resp, err := fetch("http://localhost:9876/")
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", body)
}

func fetch(url string) (*http.Response, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	client := &http.Client{
		Timeout:   5 * time.Second,
		Transport: tr,
	}

	return client.Get(url)
}

func mux() *http.ServeMux {
	r := http.NewServeMux()
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tpl := "Protocol: %s, Host: %s, Method: %s, Path: %s"
		_, _ = fmt.Fprintf(w, tpl, r.Proto, r.Host, r.Method, r.URL.Path)
	})
	return r
}
Output:

Protocol: HTTP/1.1, Host: localhost:9876, Method: GET, Path: /

func (*Server) StartAutoTLS

func (s *Server) StartAutoTLS() error

StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.

func (*Server) StartTLS

func (s *Server) StartTLS() (err error)

StartTLS starts HTTPS server.

The certificate and matching private key must provide by setting the TLS option.

Either pair of TLS.CertFile and TLS.KeyFile or TLS.Cert and TLS.Key must be provided.

Example
package main

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/foodarchive/truffls/pkg/server"
)

func main() {
	srv := server.New(
		mux(),
		server.WithAddr("", "8765"),
		server.WithCertFile(
			"./testdata/localhost.crt",
			"./testdata/localhost.key",
		),
	)

	defer func() {
		if err := srv.Shutdown(); err != nil {
			log.Fatal(err)
		}
	}()

	go func() {
		if err := srv.StartTLS(); err != nil {
			log.Fatal(err)
		}
	}()

	time.Sleep(20 * time.Millisecond)

	resp, err := fetch("https://localhost:8765/")
	if err != nil {
		log.Fatal(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", body)
}

func fetch(url string) (*http.Response, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	client := &http.Client{
		Timeout:   5 * time.Second,
		Transport: tr,
	}

	return client.Get(url)
}

func mux() *http.ServeMux {
	r := http.NewServeMux()
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tpl := "Protocol: %s, Host: %s, Method: %s, Path: %s"
		_, _ = fmt.Fprintf(w, tpl, r.Proto, r.Host, r.Method, r.URL.Path)
	})
	return r
}
Output:

Protocol: HTTP/1.1, Host: localhost:8765, Method: GET, Path: /

func (*Server) Stop

func (s *Server) Stop()

Stop stopping the signal handler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL