91 lines
2.1 KiB
Go
91 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"log"
|
|
"io/ioutil"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
type (
|
|
Config struct {
|
|
Address string // which address should be listened on
|
|
Port int // the port to listen for the admin panel
|
|
Connection string // the URL to the database
|
|
TemplatePath string // path to the templates
|
|
}
|
|
Middleware struct {
|
|
admin *AdminPages
|
|
site *SitePages
|
|
}
|
|
)
|
|
|
|
var (
|
|
admin_url_prefix = "/admin"
|
|
)
|
|
|
|
// logger works as a middleware here
|
|
func (l Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
w.Header()["Content-Type"] = []string{"text/html"}
|
|
|
|
if strings.HasPrefix(r.URL.Path, admin_url_prefix) {
|
|
l.admin.ServeHTTP(w, r)
|
|
} else {
|
|
l.site.ServeHTTP(w, r)
|
|
}
|
|
|
|
log.Print(r.URL.Path, ";", time.Since(start))
|
|
}
|
|
|
|
func main() {
|
|
var config_path string
|
|
flag.StringVar(&config_path, "config", "config.yml", "path to the config file")
|
|
flag.Parse()
|
|
|
|
config, err := readConfig(config_path)
|
|
if err != nil {
|
|
log.Println("Error with config file: ", err)
|
|
os.Exit(1)
|
|
}
|
|
if err := templates_load(config.TemplatePath); err != nil {
|
|
log.Printf("Error when loading the templates: %v", err)
|
|
os.Exit(1)
|
|
}
|
|
if err := db_open(config.Connection); err != nil {
|
|
log.Printf("Error when opening database connection: %v", err)
|
|
os.Exit(1)
|
|
}
|
|
defer DB.Close()
|
|
|
|
start_server(config)
|
|
}
|
|
|
|
// Reads the config from config_path and returns the settings.
|
|
func readConfig(config_path string) (*Config, error) {
|
|
if config_path == "" {
|
|
return nil, errors.New("No config path given!")
|
|
}
|
|
file, err := ioutil.ReadFile(config_path)
|
|
if err != nil { return nil, err }
|
|
|
|
config := Config{}
|
|
if err := yaml.Unmarshal(file, &config); err != nil {
|
|
return nil, err
|
|
}
|
|
return &config, nil
|
|
}
|
|
|
|
// start the server with access log
|
|
func start_server(config *Config) {
|
|
middleware := Middleware{NewAdminPages(), NewSitePages()}
|
|
log.Print(http.ListenAndServe(fmt.Sprintf("%v:%v", config.Address, config.Port), middleware))
|
|
}
|