caddy/modules/caddyhttp/caddyhttp.go

109 lines
2.2 KiB
Go
Raw Normal View History

2019-03-27 02:00:54 +08:00
package caddyhttp
import (
2019-03-27 09:42:52 +08:00
"context"
2019-03-27 05:45:51 +08:00
"fmt"
2019-03-27 02:00:54 +08:00
"log"
2019-03-27 05:45:51 +08:00
"net"
"net/http"
"strconv"
"strings"
"time"
2019-03-27 02:00:54 +08:00
"bitbucket.org/lightcodelabs/caddy2"
)
func init() {
err := caddy2.RegisterModule(caddy2.Module{
Name: "http",
2019-03-27 05:45:51 +08:00
New: func() (interface{}, error) { return new(httpModuleConfig), nil },
2019-03-27 02:00:54 +08:00
})
if err != nil {
log.Fatal(err)
}
}
type httpModuleConfig struct {
Servers map[string]httpServerConfig `json:"servers"`
2019-03-27 09:42:52 +08:00
servers []*http.Server
2019-03-27 02:00:54 +08:00
}
2019-03-27 05:45:51 +08:00
func (hc *httpModuleConfig) Run() error {
2019-03-27 09:42:52 +08:00
// fmt.Printf("RUNNING: %#v\n", hc)
2019-03-27 05:45:51 +08:00
for _, srv := range hc.Servers {
2019-03-27 09:42:52 +08:00
s := &http.Server{
2019-03-27 05:45:51 +08:00
ReadTimeout: time.Duration(srv.ReadTimeout),
ReadHeaderTimeout: time.Duration(srv.ReadHeaderTimeout),
}
for _, lnAddr := range srv.Listen {
proto, addrs, err := parseListenAddr(lnAddr)
if err != nil {
return fmt.Errorf("parsing listen address '%s': %v", lnAddr, err)
}
for _, addr := range addrs {
ln, err := caddy2.Listen(proto, addr)
if err != nil {
return fmt.Errorf("%s: listening on %s: %v", proto, addr, err)
}
go s.Serve(ln)
hc.servers = append(hc.servers, s)
2019-03-27 05:45:51 +08:00
}
}
}
return nil
}
2019-03-27 09:42:52 +08:00
func (hc *httpModuleConfig) Cancel() error {
for _, s := range hc.servers {
err := s.Shutdown(context.Background()) // TODO
if err != nil {
return err
}
}
return nil
}
2019-03-27 05:45:51 +08:00
func parseListenAddr(a string) (proto string, addrs []string, err error) {
proto = "tcp"
2019-03-27 09:42:52 +08:00
if idx := strings.Index(a, "/"); idx >= 0 {
2019-03-27 05:45:51 +08:00
proto = strings.ToLower(strings.TrimSpace(a[:idx]))
2019-03-27 09:42:52 +08:00
a = a[idx+1:]
2019-03-27 05:45:51 +08:00
}
var host, port string
host, port, err = net.SplitHostPort(a)
if err != nil {
return
}
ports := strings.SplitN(port, "-", 2)
if len(ports) == 1 {
ports = append(ports, ports[0])
}
var start, end int
start, err = strconv.Atoi(ports[0])
if err != nil {
return
}
end, err = strconv.Atoi(ports[1])
if err != nil {
return
}
if end < start {
err = fmt.Errorf("end port must be greater than start port")
return
}
for p := start; p <= end; p++ {
addrs = append(addrs, net.JoinHostPort(host, fmt.Sprintf("%d", p)))
}
return
}
2019-03-27 02:00:54 +08:00
type httpServerConfig struct {
2019-03-27 05:45:51 +08:00
Listen []string `json:"listen"`
ReadTimeout caddy2.Duration `json:"read_timeout"`
ReadHeaderTimeout caddy2.Duration `json:"read_header_timeout"`
2019-03-27 02:00:54 +08:00
}