예제 #1
0
func main() {
	flag.Parse()
	loadConfig()
	gorest.RegisterService(new(DreamService))
	var err error

	webClient, err = spicerack.LogIntoSaltyBet(illumEmail, illumPass)
	if err != nil {
		fmt.Printf("Error logging into Salty Bet: %v\n", err)
	}

	if !*fastcgi {
		fmt.Println("Running Locally")
		static := []string{"index", "search", "ds.js", "s.js", "ta.css"}
		for _, p := range static {
			http.HandleFunc(fmt.Sprintf("/%s", p), staticPage)
		}
		http.Handle("/", gorest.Handle())
		fmt.Println(http.ListenAndServe(":9000", nil))
	} else {
		fmt.Println("Running as FastCGI")
		l, _ := net.Listen("tcp", ":9000")
		fmt.Println(fcgi.Serve(l, gorest.Handle()))
	}
}
예제 #2
0
파일: app.go 프로젝트: Neeke/beego
func (app *App) Run() {
	addr := HttpAddr

	if HttpPort != 0 {
		addr = fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
	}

	BeeLogger.Info("Running on %s", addr)

	var (
		err error
		l   net.Listener
	)

	if UseFcgi {
		if HttpPort == 0 {
			l, err = net.Listen("unix", addr)
		} else {
			l, err = net.Listen("tcp", addr)
		}
		if err != nil {
			BeeLogger.Critical("Listen: ", err)
		}
		err = fcgi.Serve(l, app.Handlers)
	} else {
		if EnableHotUpdate {
			server := &http.Server{
				Handler:      app.Handlers,
				ReadTimeout:  time.Duration(HttpServerTimeOut) * time.Second,
				WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
			}
			laddr, err := net.ResolveTCPAddr("tcp", addr)
			if nil != err {
				BeeLogger.Critical("ResolveTCPAddr:", err)
			}
			l, err = GetInitListner(laddr)
			theStoppable = newStoppable(l)
			err = server.Serve(theStoppable)
			theStoppable.wg.Wait()
			CloseSelf()
		} else {
			s := &http.Server{
				Addr:         addr,
				Handler:      app.Handlers,
				ReadTimeout:  time.Duration(HttpServerTimeOut) * time.Second,
				WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
			}
			if HttpTLS {
				err = s.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
			} else {
				err = s.ListenAndServe()
			}
		}
	}

	if err != nil {
		BeeLogger.Critical("ListenAndServe: ", err)
		time.Sleep(100 * time.Microsecond)
	}
}
예제 #3
0
파일: server.go 프로젝트: yulon/gotor
func FastCGI(addr string, hf http.HandlerFunc) error {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	return fcgi.Serve(ln, hf)
}
예제 #4
0
func main() {
	log.SetPrefix("gff3validating ")
	log.Println("STARTED")
	fcgi.Serve(nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Println("Got request")
		reader, err := r.MultipartReader()
		if err != nil {
			view.ErrorTmpl.Execute(w, view.Error{err, "The file was not sent or received properly"})
			log.Println(err)
			return
		}

		var fname string

		for {
			part, err := reader.NextPart()
			if err == io.EOF {
				log.Printf("EOF\n")
				break
			}
			if err != nil {
				view.ErrorTmpl.Execute(w, view.Error{err, "The file was not sent or received properly"})
				log.Println(err)
				return
			}
			switch part.FormName() {
			case "soubor":
				f, err := ioutil.TempFile("", "gff")
				if err != nil {
					view.ErrorTmpl.Execute(w, view.Error{err, "Could not create a temporary file"})
					log.Println(err)
				}
				fname = f.Name()
				_, err = io.Copy(f, part)
				f.Close()
			default:
				log.Printf("Unexpected FormName %v\n", part.FormName())
			}

			// 			l/*og.Println("FormName: " + part.FormName())
			// 			log.Println*/("FileName: " + part.FileName())
			part.Close()
		}

		if fname != "" {
			log.Println("file", fname, "created")
			results, err := services.Validate(fname)
			if err != nil {
				view.ErrorTmpl.Execute(w, view.Error{err, "Running the gt gff3validator command failed"})
			} else {
				view.ResultsTmpl.Execute(w, results)
			}

			err = os.Remove(fname)
			if err != nil {
				log.Println(err)
			}
		}
	}))
}
예제 #5
0
func main() {
	log.Print("main")

	listener, _ := net.Listen("tcp", ":9000")
	fcgi.Serve(listener, rooter(goji.DefaultMux))

}
예제 #6
0
func main() {
	l, err := net.Listen("tcp", ":9000")
	if err != nil {
		return
	}
	fcgi.Serve(l, Route(goji.DefaultMux))
}
예제 #7
0
func main() {
	router := mux.NewRouter()

	router.HandleFunc(flagURIPrefix, indexHandler).
		Methods("GET").
		Name("home")

	router.HandleFunc(flagURIPrefix+"/ls", listHandler).
		Methods("GET").
		Name("list")

	router.HandleFunc(flagURIPrefix+"/rm/{path}", deleteHandler).
		Methods("GET").
		Name("rm")

	listener, err := net.Listen("unix", flagFCGISocket)
	if err != nil {
		log.Fatal("Failed to listen: ", err)
	}
	defer listener.Close()
	err = fcgi.Serve(listener, router)
	if err != nil {
		log.Fatal("Failed to serve on socket: ", err)
	}

	return

}
예제 #8
0
파일: beego.go 프로젝트: redoufu/beego
func (app *App) Run() {
	addr := fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
	var (
		err error
		l   net.Listener
	)
	if UseFcgi {
		l, err = net.Listen("tcp", addr)
		if err != nil {
			BeeLogger.Fatal("Listen: ", err)
		}
		err = fcgi.Serve(l, app.Handlers)
	} else {
		server := &http.Server{Handler: app.Handlers}
		laddr, err := net.ResolveTCPAddr("tcp", addr)
		if nil != err {
			BeeLogger.Fatal("ResolveTCPAddr:", err)
		}
		l, err = GetInitListner(laddr)
		theStoppable = newStoppable(l)
		err = server.Serve(theStoppable)
		theStoppable.wg.Wait()
		CloseSelf()
	}
	if err != nil {
		BeeLogger.Fatal("ListenAndServe: ", err)
	}
}
예제 #9
0
파일: main.go 프로젝트: demdxx/gosubland
func main() {
	// Run HTTP server
	fmt.Println("Domain: " + config.String("server.domain"))
	fmt.Println("Start rotator server: " + *flagHost)

	if *flagFastCGI {
		fmt.Println("FastCGI Mode: ON")
	}
	if *flagDebug {
		fmt.Println("Debug Mode: ON")
	}

	// Run server
	if *flagFastCGI {
		if tcp, err := net.Listen("tcp", *flagHost); nil == err {
			fcgi.Serve(tcp, router.NewRouter(*flagDebug))
		} else if err != nil {
			log.Fatal(err)
		}
	} else {
		var err error
		http.Handle("/", router.NewRouter(*flagDebug))
		http.Handle("/public/", http.FileServer(http.Dir(*flagBaseDir)))
		if err = http.ListenAndServe(*flagHost, nil); nil != err {
			log.Fatal(err)
		}
	}
}
예제 #10
0
파일: fizbuz.go 프로젝트: aoeu/fizbuz.biz
func main() {
	args := struct{ port string }{}
	flag.StringVar(&args.port, "port", "", "The port to serve on.")
	flag.Parse()
	cache = make(map[string]string, 100)
	for i := 0; i < 101; i++ {
		s := strconv.Itoa(i)
		t := s
		f, b := i%3 == 0, i%5 == 0
		if f || b {
			t = ""
		}
		if f {
			t = "Fizz"
		}
		if b {
			t += "Buzz"
		}
		cache[s] = t + "\n"
	}
	http.HandleFunc("/", handler)
	switch {
	case args.port != "":
		if err := http.ListenAndServe(args.port, nil); err != nil {
			log.Fatal(err)
		}
	default:
		if err := fcgi.Serve(nil, nil); err != nil {
			log.Fatal(err)
		}
	}
}
예제 #11
0
func main() {
	err := fcgi.Serve(nil, http.HandlerFunc(handler))
	//err := http.ListenAndServe("localhost:1234", http.HandlerFunc(handler))
	if err != nil {
		log.Fatal(err)
	}
}
예제 #12
0
func web_start() {
	mux := http.NewServeMux()
	mux.HandleFunc("/api/1/group", groupV1)
	mux.HandleFunc("/api/1/status", statusV1)
	mux.HandleFunc("/tablet", user_interface_tabletV1)
	mux.HandleFunc("/phone", user_interface_phoneV1)
	mux.HandleFunc("/", static_root)
	if local_web_server_flag {
		hostname := fmt.Sprintf(":%d", web_bind_port)
		start_message := fmt.Sprintf("Starting local hued-web on %s\n", hostname)
		fmt.Println(start_message)
		glog.Infof(start_message)
		http.ListenAndServe(hostname, mux)
	} else {
		hostname := fmt.Sprintf("%s:%d", web_bind_address, web_bind_port)
		l, err := net.Listen("tcp", hostname)
		if err == nil {
			start_message := fmt.Sprintf("Starting hued-web on %s\n", hostname)
			fmt.Println(start_message)
			glog.Infof(start_message)
			fcgi.Serve(l, mux)
		} else {
			glog.Error("Error starting server, is the port already in use?")
		}
	}
}
예제 #13
0
func main() {

	socket := "/home/vagrant/dev/src/github.com/r-fujiwara/goroutine-fcgi/go-home.sock"
	userid := 33
	groupid := 33

	_ = syscall.Umask(0177)

	l, err := net.Listen("unix", socket)

	_ = syscall.Chown(socket, userid, groupid)

	defer l.Close()

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

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for sig := range c {
			log.Printf("Captured: %v", sig)
			l.Close()
		}
	}()

	mux := http.NewServeMux()
	mux.HandleFunc("/", hello)
	fcgi.Serve(l, mux)
}
예제 #14
0
파일: ssss.go 프로젝트: jango2015/ssss
func (app *App) Run() {
	app.buildTemplate()
	if app.config.HttpAddr == "" {
		app.config.HttpAddr = "0.0.0.0"
	}
	addr := fmt.Sprintf("%s:%d", app.config.HttpAddr, app.config.HttpPort)
	var err error

	for {
		if app.config.UseFcgi {
			l, e := net.Listen("tcp", addr)
			if e != nil {
				log.Print("Listen: ", e)
			}
			//log.Print("UseFcgi, fcgi.Serve")
			err = fcgi.Serve(l, app.Handlers)
		} else {
			//log.Print("http.ListenAndServe")
			//err = http.ListenAndServe(addr, app.Handlers)
			err = httpListenAndServe(addr, app.Handlers, app.config.ReadTimeout, app.config.WriteTimeout)
		}
		if err != nil {
			log.Print("ListenAndServe: ", err)
			//panic(err)
		}
		time.Sleep(time.Second * 2)
	}
}
예제 #15
0
// NewServer takes a host or ip address string, a port number, read timeout
// (in secords), along with a map defining url string patterns, and their
// corresponding response functions. NewServer sets each map entry into
// the HTTP multiplexer, then starts the HTTP server on the given host/ip
// address and port. The api.Server struct also provides a Logger for each
// response function to use, to log warnings, errors, and other information.
func NewServer(host, transport string, port, timeout int, useFcgi bool, handlers map[string]func(http.ResponseWriter, *http.Request)) {

	mux := http.NewServeMux()
	for pattern, handler := range handlers {
		mux.Handle(pattern, http.HandlerFunc(handler))
	}

	s := &http.Server{
		Addr:        fmt.Sprintf("%s:%d", host, port),
		Handler:     mux,
		ReadTimeout: time.Duration(timeout) * time.Second, // to prevent abuse of "keep-alive" requests by clients
	}

	Srv = &Server{
		mux:       mux,
		s:         s,
		Logger:    log.New(os.Stdout, "", log.Ldate|log.Ltime),
		Transport: transport,
	}

	if useFcgi {
		// create a listener for the incoming FastCGI requests
		listener, err := net.Listen(Srv.Transport, Srv.s.Addr)
		if err != nil {
			Srv.Logger.Fatal(err)
		}
		fcgi.Serve(listener, Srv.mux)
	} else {
		// serve requests using the default http.Server
		Srv.s.ListenAndServe()
	}
}
예제 #16
0
파일: main.go 프로젝트: scds/eimbu
func main() {
	if !flag.Parsed() {
		flag.Parse()
	}
	var regexHandler = NewHttpHandlerRegexMatcher()

	http.Handle("/", http.StripPrefix(*prefix, regexHandler))

	regexHandler.Handle("/test", HttpHandlerRestHandler{5})
	regexHandler.Handle("/test/", HttpHandlerRestHandler{5})
	regexHandler.Handle("/test/{id}", HttpHandlerRestHandler{5})

	regexHandler.Handle("/ses/{request}", oauthFlowHandler{})

	var socket = *socket

	os.Remove(socket)

	oldUmask := syscall.Umask(000)
	l, err := net.Listen("unix", socket)
	syscall.Umask(oldUmask)
	if err != nil {
		panic(err)
	}

	panic(fcgi.Serve(l, http.DefaultServeMux))
}
예제 #17
0
파일: app.go 프로젝트: horryq/beego
// Run beego application.
func (app *App) Run() {
	addr := HttpAddr

	if HttpPort != 0 {
		addr = fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
	}

	BeeLogger.Info("Running on %s", addr)

	var (
		err error
		l   net.Listener
	)
	endRunning := make(chan bool, 1)

	if UseFcgi {
		if HttpPort == 0 {
			l, err = net.Listen("unix", addr)
		} else {
			l, err = net.Listen("tcp", addr)
		}
		if err != nil {
			BeeLogger.Critical("Listen: ", err)
		}
		err = fcgi.Serve(l, app.Handlers)
	} else {
		app.Server.Addr = addr
		app.Server.Handler = app.Handlers
		app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second
		app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second

		if EnableHttpTLS {
			go func() {
				if HttpsPort != 0 {
					app.Server.Addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort)
				}
				err := app.Server.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
				if err != nil {
					BeeLogger.Critical("ListenAndServeTLS: ", err)
					time.Sleep(100 * time.Microsecond)
					endRunning <- true
				}
			}()
		}

		if EnableHttpListen {
			go func() {
				err := app.Server.ListenAndServe()
				if err != nil {
					BeeLogger.Critical("ListenAndServe: ", err)
					time.Sleep(100 * time.Microsecond)
					endRunning <- true
				}
			}()
		}
	}

	<-endRunning
}
예제 #18
0
func main() {
	flag.StringVar(&Config.bind, "bind", "127.0.0.1:8080",
		"host to bind to (default: 127.0.0.1:8080)")
	flag.StringVar(&Config.filesDir, "filespath", "files/",
		"path to files directory")
	flag.StringVar(&Config.metaDir, "metapath", "meta/",
		"path to metadata directory")
	flag.BoolVar(&Config.noLogs, "nologs", false,
		"remove stdout output for each request")
	flag.BoolVar(&Config.allowHotlink, "allowhotlink", false,
		"Allow hotlinking of files")
	flag.StringVar(&Config.siteName, "sitename", "linx",
		"name of the site")
	flag.StringVar(&Config.siteURL, "siteurl", "http://"+Config.bind+"/",
		"site base url (including trailing slash)")
	flag.Int64Var(&Config.maxSize, "maxsize", 4*1024*1024*1024,
		"maximum upload file size in bytes (default 4GB)")
	flag.StringVar(&Config.certFile, "certfile", "",
		"path to ssl certificate (for https)")
	flag.StringVar(&Config.keyFile, "keyfile", "",
		"path to ssl key (for https)")
	flag.BoolVar(&Config.fastcgi, "fastcgi", false,
		"serve through fastcgi")
	flag.BoolVar(&Config.remoteUploads, "remoteuploads", false,
		"enable remote uploads")
	flag.StringVar(&Config.contentSecurityPolicy, "contentsecuritypolicy",
		"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; referrer none;",
		"value of default Content-Security-Policy header")
	flag.StringVar(&Config.fileContentSecurityPolicy, "filecontentsecuritypolicy",
		"default-src 'none'; img-src 'self'; object-src 'self'; media-src 'self'; sandbox; referrer none;",
		"value of Content-Security-Policy header for file access")
	flag.StringVar(&Config.xFrameOptions, "xframeoptions", "SAMEORIGIN",
		"value of X-Frame-Options header")
	flag.Parse()

	mux := setup()

	if Config.fastcgi {
		listener, err := net.Listen("tcp", Config.bind)
		if err != nil {
			log.Fatal("Could not bind: ", err)
		}

		log.Printf("Serving over fastcgi, bound on %s, using siteurl %s", Config.bind, Config.siteURL)
		fcgi.Serve(listener, mux)
	} else if Config.certFile != "" {
		log.Printf("Serving over https, bound on %s, using siteurl %s", Config.bind, Config.siteURL)
		err := graceful.ListenAndServeTLS(Config.bind, Config.certFile, Config.keyFile, mux)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Printf("Serving over http, bound on %s, using siteurl %s", Config.bind, Config.siteURL)
		err := graceful.ListenAndServe(Config.bind, mux)
		if err != nil {
			log.Fatal(err)
		}
	}
}
예제 #19
0
파일: webapp.go 프로젝트: haegyung/tattoo
func (app *App) RunCGI(port int) {
	app.Port = port
	l, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port))
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
	fcgi.Serve(l, app.Handler)
}
예제 #20
0
func startFCGIApp(t *testing.T, addr string) (net.Listener, error) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		t.Fatal(err)
	}
	go fcgi.Serve(l, http.HandlerFunc(serve))
	return l, nil
}
예제 #21
0
func (s *Server) turnOnFastCGI() {
	listener, err := net.Listen("tcp", s.Host+":"+s.Port)
	if err != nil {
		panic(err.Error())
	}
	srv := new(Server)
	fcgi.Serve(listener, srv)
}
func main() {
	l, err := net.Listen("tcp", ":9000")
	if err != nil {
		return
	}
	http.HandleFunc("/", mainHandler)
	fcgi.Serve(l, nil)
}
예제 #23
0
func newApp(network, address string, fn http.HandlerFunc) (l net.Listener, err error) {
	l, err = net.Listen(network, address)
	if err != nil {
		return
	}
	go fcgi.Serve(l, http.HandlerFunc(fn))
	return
}
예제 #24
0
// main is the entry point of the program.
func main() {
	log.SetFlags(log.Ldate | log.Ltime)

	// command line arguments.
	configPath := flag.String("config-file", "",
		"Path to a configuration file.")
	logPath := flag.String("log-file", "",
		"Path to a log file.")
	flag.Parse()
	// config file is required.
	if len(*configPath) == 0 {
		log.Print("You must specify a configuration file.")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if len(*logPath) == 0 {
		log.Print("You must specify a log file.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	// open log file.
	// don't use os.Create() because that truncates.
	logFh, err := os.OpenFile(*logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		log.Printf("Failed to open log file: %s: %s", *logPath, err.Error())
		os.Exit(1)
	}
	log.SetOutput(logFh)

	// load up our settings.
	var settings Config
	err = config.GetConfig(*configPath, &settings)
	if err != nil {
		log.Printf("Failed to retrieve config: %s", err.Error())
		os.Exit(1)
	}

	// start listening.
	var listenHostPort = fmt.Sprintf("%s:%d", settings.ListenHost,
		settings.ListenPort)
	listener, err := net.Listen("tcp", listenHostPort)
	if err != nil {
		log.Print("Failed to open port: " + err.Error())
		os.Exit(1)
	}

	httpHandler := HttpHandler{settings: &settings}

	// XXX: this will serve requests forever - should we have a signal
	//   or a method to cause this to gracefully stop?
	log.Print("Starting to serve requests.")
	err = fcgi.Serve(listener, httpHandler)
	if err != nil {
		log.Print("Failed to start serving HTTP: " + err.Error())
		os.Exit(1)
	}
}
예제 #25
0
func main() {
	var (
		flListen         = flag.String("listen", "localhost:8901", "server listen address")
		flMode           = flag.String("mode", "http", "server mode (http or fcgi)")
		flProtocol       = flag.String("protocol", "tcp", "listener protocol, only valid for fcgi mode")
		flConfig         = flag.String("config", "", "path to configuration file")
		flSsl            = flag.Bool("ssl", false, "enable ssl, requires certificate and key files")
		flCertFile       = flag.String("cert", "", "ssl certificate")
		flKeyFile        = flag.String("ssl-key", "", "ssl private key")
		flReadTimeout    = flag.Duration("read-timeout", 10*time.Second, "read timeout")
		flWriteTimeout   = flag.Duration("write-timeout", 10*time.Second, "write timeout")
		flMaxHeaderBytes = flag.Int("buffer", 1<<20, "maximum header bytes")
		flBase           = flag.String("base", "", "path to base directory")
	)

	flag.Parse()

	handler, err := handlerFactory(*flConfig, *flBase)
	if err != nil {
		log.Fatalf("An error occured while initializing the application: %s", err)
	}

	switch *flMode {
	case "http":
		s := &http.Server{
			Addr:           *flListen,
			Handler:        handler,
			ReadTimeout:    *flReadTimeout,
			WriteTimeout:   *flWriteTimeout,
			MaxHeaderBytes: *flMaxHeaderBytes,
		}

		if *flSsl {
			if *flCertFile == "" || *flKeyFile == "" {
				log.Fatalf("Requires SSL certificate and key files for SSL mode")
			}

			err = s.ListenAndServeTLS(*flCertFile, *flKeyFile)
		} else {
			err = s.ListenAndServe()
		}

		if err != nil {
			log.Fatal(err)
		}
	case "fcgi":
		listener, err := net.Listen(*flProtocol, *flListen)
		if err != nil {
			log.Fatal(err)
		}
		err = fcgi.Serve(listener, handler)
		if err != nil {
			log.Fatal(err)
		}
	default:
		log.Fatalf("Invalid server mode: %v (Valid modes are 'http' and 'fcgi')", *flMode)
	}
}
예제 #26
0
func handleListners(cl chan net.Listener) {

	for v := range cl {
		go func(l net.Listener) {
			srv := new(FastCGIServer)
			fcgi.Serve(l, srv)
		}(v)
	}
}
예제 #27
0
// Starts up Luminos.
func main() {
	flag.Parse()

	if *flagHelp == true {
		fmt.Printf("Showing %v usage.\n", os.Args[0])
		flag.PrintDefaults()
		return
	}

	if *flagVersion == true {
		fmt.Printf("%v version: %s\n", os.Args[0], version)
		return
	}

	hosts = make(map[string]*host.Host)

	settings = yaml.Open(*flagSettings)

	serverType := settings.GetString("server/type")

	domain := "unix"
	address := settings.GetString("server/socket")

	if address == "" {
		domain = "tcp"
		address = fmt.Sprintf("%s:%d", settings.GetString("server/bind"), settings.GetInt("server/port"))
	}

	listener, err := net.Listen(domain, address)

	if err != nil {
		log.Fatalf("Failed to bind on %s.", address)
	}

	defer listener.Close()

	switch serverType {
	case "fastcgi":
		if err == nil {
			log.Printf("FastCGI server listening at %s.", address)
			fcgi.Serve(listener, &Server{})
		} else {
			log.Fatalf("Failed to start FastCGI server.")
		}
	case "standalone":
		if err == nil {
			log.Printf("HTTP server listening at %s.", address)
			http.Serve(listener, &Server{})
		} else {
			log.Fatalf("Failed to start HTTP server.")
		}
	default:
		log.Fatalf("Unknown server type %s.", serverType)
	}

	log.Printf("Exiting...")
}
예제 #28
0
파일: main.go 프로젝트: jnlopar/shawty
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// read configurations
	confKeys := []string{"SHAWTY_PORT", "SHAWTY_DB", "SHAWTY_DOMAIN", "SHAWTY_MODE", "SHAWTY_LPM", "SHAWTY_LOG_DIR"}
	config := make(map[string]string)
	for _, k := range confKeys {
		config[k] = os.Getenv(k)
	}

	// setup logger
	log.SetDir(config["SHAWTY_LOG_DIR"])

	// setup data
	random := utils.NewBestRand()
	shawties, err := data.NewMySh(random, config["SHAWTY_DB"])
	if err != nil {
		log.Error("Cannot create MySh")
		return
	}
	defer shawties.Close()

	// register routes
	home := web.NewHomeController(config)
	shawtyjs := web.NewShawtyJSController(config, shawties)
	shortID := web.NewShortIDController(config, shawties)

	// setup HTTP server
	router := mux.NewRouter()
	router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	router.Handle("/", home)
	router.Handle("/shawty.js", shawtyjs)
	router.Handle("/{shortID:[A-Za-z0-9]+}", shortID)

	var port = config["SHAWTY_PORT"]
	if port == "" {
		port = "80"
	}

	l, err := net.Listen("tcp", "0.0.0.0:"+port)
	if err != nil {
		log.Errorf("Cannot listen at %s", port)
		fmt.Println(err)
		return
	}
	defer l.Close()
	log.Infof("Listening at %s", port)

	runMode := config["SHAWTY_MODE"]
	switch runMode {
	case "fcgi":
		fcgi.Serve(l, router)
	default:
		http.Serve(l, router)
	}
}
예제 #29
0
파일: server.go 프로젝트: swetland/goweb
func main() {
	var cfg misc.Configuration
	cfg.AddSection("google-auth", &config_google_auth)
	cfg.AddSection("server", &config)

	if len(os.Args) != 2 {
		log.Fatal("server: no configuration file specified")
	}
	cfgfile := os.Args[1]

	log.Printf("server: loading configuration")
	file, err := os.Open(cfgfile)
	if err != nil {
		log.Fatal(err)
	}

	err = cfg.Parse(file)
	file.Close()
	if err != nil {
		log.Fatal(err)
	}

	if !strings.HasSuffix(config.BaseDir, "/") {
		config.BaseDir += "/"
	}
	config.UserDir = config.BaseDir + "user/"
	config.DataDir = config.BaseDir + "data/"
	config.FileDir = config.BaseDir + "file/"

	sock := config.Socket
	addr := config.Address
	if len(sock) == 0 && len(addr) == 0 {
		log.Fatalf("server: %s: must select either server.address"+
			" or server.socket", cfgfile)
	}
	if len(sock) != 0 && len(addr) != 0 {
		log.Fatalf("server: %s: cannot use both server.address"+
			" and server.socket", cfgfile)
	}

	if len(sock) != 0 {
		os.Remove(sock)
		s, err := net.Listen("unix", sock)
		os.Chmod(sock, 0666)
		if err != nil {
			log.Fatal(err)
		}

		err = fcgi.Serve(s, http.HandlerFunc(rootHandler))
		if err != nil {
			log.Fatal(err)
		}
	} else {
		http.ListenAndServe(addr, http.HandlerFunc(rootHandler))
	}
}
예제 #30
0
파일: main.go 프로젝트: horie1024/fhack
func main() {

	l, _ := net.Listen("tcp", ":9000")

	http.HandleFunc("/api", Index)
	//http.HandleFunc("/temp") // 温度
	// ハーストで無いなら、温度でplaceのサーチ範囲変える

	fcgi.Serve(l, nil)
}