Exemplo n.º 1
0
func routeHandler(router helpers.RegexpRouter) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		router.ServeHTTP(w, r)
		log.Printf("%s %s %s %v", r.RemoteAddr, r.Method, r.URL, time.Since(start))
	})
}
Exemplo n.º 2
0
func main() {
	var err error
	var config_file string
	flag.StringVar(&config_file, "config", "./config.cfg", "config file location")
	flag.Parse()
	cfg, err := readConfig(fmt.Sprintf("%v", config_file))
	if err != nil {
		log.Fatal(err.Error())
	}

	if lf := cfg["log_file"]; lf != "" {
		logfile, err := os.OpenFile(lf, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.FileMode(0666))
		if err != nil {
			log.Println(err.Error())
		} else {
			log.SetOutput(logfile)
		}
	}

	if pidfile := cfg["pid_file"]; pidfile != "" {
		file, err := os.Create(pidfile)
		if err != nil {
			log.Fatal(err.Error())
		}

		file.WriteString(fmt.Sprintln(os.Getpid()))
		file.Close()
	}

	models.ConnectDB(cfg["dbhost"], cfg["dbport"], cfg["dbuser"], cfg["dbpass"], cfg["dbname"])

	assetServer := http.FileServer(http.Dir("assets"))
	http.Handle("/assets/", http.StripPrefix("/assets/", assetServer))

	router := new(helpers.RegexpRouter)
	router.AddRoute("/api/countries.json", countriesHandler)
	router.AddRoute("/api/countries/show.json", countryHandler)
	router.AddRoute("/.*", pageHandler)

	http.Handle("/", routeHandler(*router))

	listen := "127.0.0.1:8080"
	fmt.Println(fmt.Sprintf("listening on %s", listen))
	err = http.ListenAndServe(listen, nil)
	if err != nil {
		panic("http.ListenAndServe: " + err.Error())
	}
}