shizaru/main.go

79 lines
1.9 KiB
Go

package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
)
func main() {
os.Exit(main_body())
}
func main_body() int {
var conf_file string
// Parse args and read config
flag.StringVar(&conf_file, "c", "", "Path to config file")
flag.Parse()
if conf_file == "" {
_, err := os.Stat("/etc/shizaru.conf")
if !os.IsNotExist(err) {
conf_file = "/etc/shizaru.conf"
}
}
config, err := getConfig(conf_file)
if err != nil {
fmt.Println("Error reading config file " + conf_file)
return 1
}
// Open logfile
logfile, err := os.OpenFile(config.LogPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening log file " + config.LogPath + ".")
return 2
}
defer logfile.Close()
errs := make(chan error, 2)
// Start the HTTP server, which redirect all incoming connections to HTTPS
http.HandleFunc("/", LoggingWrapper(logfile, GetHandler(config)))
http_server := &http.Server{Addr: ":"+strconv.Itoa(config.HttpPort), Handler: http.HandlerFunc(GetRedirectTLSHandler(config))}
go func() {
errs <- http_server.ListenAndServe()
}()
tlscfg := &tls.Config{
MinVersion: tls.VersionTLS10,
}
// Start the HTTPS server which actually handles most traffic.
https_server := &http.Server{Addr: ":"+strconv.Itoa(config.HttpsPort), Handler: nil, TLSConfig: tlscfg}
go func() {
errs <- https_server.ListenAndServeTLS(config.CertPath, config.KeyPath)
}()
fmt.Println("Listening on ports " + strconv.Itoa(config.HttpPort) + " and " + strconv.Itoa(config.HttpsPort) + "...")
// Listen for signals to gracefully shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
// Wait for a signal or an error
select {
case <-stop:
fmt.Println("Shutting down!")
http_server.Shutdown(context.Background())
https_server.Shutdown(context.Background())
case err := <-errs:
log.Println("Fatal: " + err.Error())
}
return 0
}