Exemplo n.º 1
0
Arquivo: main.go Projeto: sporto/kic
func main() {
	// err := godotenv.Load()
	// if err != nil {
	// 	// production don't use an env file
	// 	log.Println("No .env file found")
	// }

	dbSession, err := api.StartDb("./")
	if err != nil {
		log.Fatal(err)
	}

	api.MapRoutes(dbSession)

	log.Print("Starting Goweb powered server...")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	listener, listenErr := net.Listen("tcp", Address)
	log.Printf("  visit: %s", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	log.Println("Routes:")
	log.Printf("%s", goweb.DefaultHttpHandler())

	// listen for exit signal i.e. ctrl + C
	signalChannel := make(chan os.Signal, 1)
	signal.Notify(signalChannel, os.Interrupt)

	go func() {

		for _ = range signalChannel {
			// sig is a ^C, handle it
			log.Println("^C")
			// stop the HTTP server
			log.Println("Stopping the server...")
			listener.Close()

			os.Exit(0)
		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s", s.Serve(listener))

}
Exemplo n.º 2
0
func listenAndServe(addr string) (err error) {
	s := &http.Server{
		Addr:           addr,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		logger.Info("Could not listen", err)
	}

	go func() {
		for _ = range c {
			listener.Close()
		}
	}()

	err = s.Serve(listener)
	return
}
Exemplo n.º 3
0
func main() {
	flag.StringVar(&basedir, "basedir", currentWorkingDirectory, "basedir")
	flag.StringVar(&address, "address", ":9090", "address")
	flag.Parse()

	basedir = basedir + "/"
	goweb.Map(ghttp.MethodPut, "/recording/{sessionid}/{tindex}", nuttyPut)
	goweb.Map(ghttp.MethodGet, "/recording/{sessionid}/rec.json", nuttyGetLength)
	goweb.Map(ghttp.MethodGet, "/recording/{sessionid}/{tindex}", nuttyGet)
	goweb.MapBefore(func(c context.Context) error {
		c.HttpResponseWriter().Header().Set("Access-Control-Allow-Origin", "*")
		c.HttpResponseWriter().Header().Set("Access-Control-Allow-Headers", "Content-Type")
		c.HttpResponseWriter().Header().Set("Access-Control-Allow-Methods", "PUT,GET")
		c.HttpResponseWriter().Header().Set("Content-Type", "application/json")
		return nil
	})

	s := &http.Server{
		Addr:           address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	log.Println("Starting server")
	log.Fatal(s.ListenAndServe())
}
Exemplo n.º 4
0
func Run() {
	// HTTP
	s := &httplib.Server{
		Addr:           gokuraku.Config.HttpPort,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", "0.0.0.0:"+gokuraku.Config.HttpPort)

	if listenErr != nil {
		log.Fatalf("Could not listen: 0.0.0.0:%s", gokuraku.Config.HttpPort)
	}

	go func() {
		for _ = range c {
			// sig is a ^C, handle it
			log.Print("Stopping the server...")
			listener.Close()

			log.Print("Tearing down...")
			log.Fatal("Finished - bye bye.  ;-)")

		}
	}()

	log.Printf("Gokuraku HTTP Server: 0.0.0.0:%s", gokuraku.Config.HttpPort)
	log.Fatalf("Error in Serve: %s", s.Serve(listener))
}
Exemplo n.º 5
0
func main() {
	log.Println("Starting server...")

	// API Endpoints
	goweb.Map("/ping", pingHandler)
	goweb.Map("/getquote/{apiKey}", AowQuote)
	// End API Endpoints

	address := ":3000"
	if port := os.Getenv("PORT"); port != "" {
		address = ":" + port
	}
	server := &http.Server{
		Addr:           address,
		Handler:        &LoggedHandler{goweb.DefaultHttpHandler()},
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	listener, listenErr := net.Listen("tcp", address)
	if listenErr != nil {
		log.Panicf("Could not listen for TCP on %s: %s", address, listenErr)
	}
	log.Println("Server loaded, check localhost" + address)
	server.Serve(listener)
}
Exemplo n.º 6
0
func HttpListenAndServe() (err error) {
	s := http.Server{
		Addr:           LISTEN_ADDR,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	goweb.Map("/cnvt", ConvertHandler)
	err = s.ListenAndServe()
	return
}
Exemplo n.º 7
0
func main() {

	syslog.Openlog("cinefade", syslog.LOG_PID, syslog.LOG_USER)

	var action string
	flag.StringVar(&action, "action", "on", "lights on/off")
	flag.Parse()

	bridge := cinefade.GetBridge(false)
	cinefade.MapRoutes(bridge)

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)
	syslog.Info("Server cinefade started")
	syslog.Infof("visit: %s", Address)

	if listenErr != nil {
		syslog.Critf("Could not listen: %s", listenErr)
		os.Exit(1)
	}

	go func() {
		for _ = range c {
			// sig is a ^C, handle it
			// stop the HTTP server
			syslog.Info("Stopping the cinefade server...")
			listener.Close()

			syslog.Info("Tearing down...")
			os.Exit(0)
		}
	}()

	syslog.Critf("Error in Serve: %s", s.Serve(listener))
	os.Exit(1)
}
Exemplo n.º 8
0
func main() {
	api.MapRoutes()

	address := ":" + os.Getenv("PORT")
	server := &http.Server{
		Addr:           address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	listener, listenErr := net.Listen("tcp", address)
	if listenErr != nil {
		panic(listenErr)
	}

	server.Serve(listener)
}
Exemplo n.º 9
0
// main initializes and starts the web server.
func main() {
	controllers.MapControllers()
	MapStaticFiles()

	log.Print("Mapped URLs, creating server...")
	address := ":" + os.Getenv("PORT")
	server := &http.Server{
		Addr:           address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Print("Created server, listening for requests.")
	listener, listenErr := net.Listen("tcp", address)
	if listenErr != nil {
		log.Printf("Could not listen for tcp connections on address %s: %s", address, listenErr.Error())
		panic(listenErr)
	}
	server.Serve(listener)
}
Exemplo n.º 10
0
func (c *Configuration) StartServer() {

	port := c.Json.Port
	if os.Getenv("PORT") != "" {
		port = os.Getenv("PORT")
		log.Print("Using environmental variable for $PORT")
	}

	c.HttpPort = port

	c.HttpServer = &http.Server{
		Addr:           port,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	b := make(chan os.Signal, 1)

	signal.Notify(b, os.Interrupt)
	listener, listenErr := net.Listen("tcp", ":"+c.HttpPort)
	log.Printf("  visit: %s", ":"+c.HttpPort)
	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}
	c.Listener = listener

	go func() {
		for _ = range b {
			c.Listener.Close()
		}

	}()
	log.Fatalf("Error in server: %s", c.HttpServer.Serve(listener))
}
Exemplo n.º 11
0
func StartService() {

	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	listener, _ := net.Listen("tcp", Address)

	iceController := new(IceController)
	greenController := new(GreenController)
	regController := new(RegController)
	preController := new(PredictController)

	goweb.MapController(regController)
	goweb.MapController(preController)
	goweb.MapController(greenController)
	goweb.MapController(iceController)

	fmt.Println("wats up")
	log.Fatalf("Error in Serve: %s", s.Serve(listener))
}
Exemplo n.º 12
0
Arquivo: main.go Projeto: catanm/gms
func main() {

	log.Info("Glasgow Memories Server")
	log.Info("=======================")

	utils.InitEnv()
	var Address = ":" + utils.EnvPort()
	var baseURL = utils.EnvUrl()

	m.Connect()
	defer m.Close()

	// prepare the decryption key
	if utils.LoadCypherKey() != nil {
		log.Error("Failed to load the decryption key.")
		return
	}

	// GOMNIAUTH
	gomniauth.SetSecurityKey(signature.RandomKey(64))
	gomniauth.WithProviders(
		facebook.New("1497244403859030", "fbbb08c47e0441bcf23ea82b5f340fe5",
			baseURL+"/api/auth/facebook/callback/"),
	)

	// Attach the DB collection references to the context in order to pass it around
	goweb.MapBefore(func(ctx context.Context) error {
		var user = m.User{}
		cookieC, err := ctx.HttpRequest().Cookie("token")
		var cookie string
		if err != nil {
			cookie = ctx.FormValue("token")
			if cookie == "" {
				return nil
			}
		} else {
			cookie = cookieC.Value
		}
		err = m.GetDB("User").Find(bson.M{"token": cookie}).One(&user)
		if err != nil {
			// log.Info("MapBefore 2 " + err.Error())
			return nil
		}
		ctx.Data()["user"] = user
		return nil
	})

	goweb.MapStatic("/static", "../static")   // This is the directory with all static UI files
	goweb.MapStatic("/uploads", "../uploads") // This is the directory where we should store uploaded files

	// ENDPOINTS
	goweb.Map("GET", "/", endpoints.Root)
	goweb.Map("POST", "api/auth/local/register", endpoints.Register)
	goweb.Map("POST", "api/auth/local/login", endpoints.Login)
	goweb.Map("GET", "api/auth/{provider}/callback", endpoints.Callback)
	goweb.Map([]string{"GET", "POST"}, "api/auth/{provider}/{action}", endpoints.Connect)
	goweb.Map("POST", "api/upload/image", endpoints.UploadImage)
	goweb.Map("GET", "api/images/get", endpoints.GetImages)
	goweb.Map("POST", "api/upload/csv", endpoints.UploadTrail)
	goweb.Map("GET", "api/trails/get", endpoints.GetTrails)
	goweb.Map("POST", "api/upload/video", endpoints.UploadVideo)
	goweb.Map("GET", "api/videos/get", endpoints.GetVideos)
	goweb.Map("GET", "api/user", endpoints.GetUserInfo)
	goweb.Map("GET", "api/stats/get", endpoints.GetStats)
	goweb.Map("GET", "api/popLocations", endpoints.GetPopularLocations)
	goweb.Map("POST", "api/upload/imagetable", endpoints.UploadImageTable)
	goweb.Map("POST", "api/upload/zip", endpoints.UploadZip)
	// TODO: Add new endpoints here

	goweb.Map(endpoints.NotFound)

	// Remove the information from the data just in case the call is intercepted
	goweb.MapAfter(func(ctx context.Context) error {
		ctx.Data()["user"] = ""
		return nil
	})

	// setup the API responder
	codecService := services.NewWebCodecService()
	codecService.RemoveCodec("text/xml")
	apiResponder := responders.NewGowebAPIResponder(codecService, goweb.Respond)
	apiResponder.StandardFieldDataKey = "data"
	apiResponder.StandardFieldStatusKey = "status"
	apiResponder.StandardFieldErrorsKey = "errors"
	goweb.API = apiResponder

	// SERVER
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    5 * time.Minute,
		WriteTimeout:   5 * time.Minute,
		MaxHeaderBytes: 1 << 20,
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)
	log.Info("Server port: " + Address)
	log.Info("Server running at: " + baseURL + "\n")
	if listenErr != nil {
		log.Error("Could not listen: " + listenErr.Error())
	}

	go func() {
		for _ = range c {
			// sig is a ^C, handle it
			// stop the HTTP server
			log.Info("Stopping the server...\n")
			listener.Close()
			log.Info("Server stopped.\n")
		}
	}()
	// begin the server
	log.Error("Error in Serve: " + s.Serve(listener).Error())
}
Exemplo n.º 13
0
func main() {

	log.SetFlags(0)
	log.Printf("Reservoir %s.%s.%s | A GOod Build Server\n", MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION)
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	log.Print("")

	var serverConfig map[string]map[string]interface{}

	err := Config_GetConfig("server", &serverConfig)
	if err != nil {
		panic(err)
	}

	useFcgi := serverConfig[Config_Environment]["fcgi"].(bool)
	addr := serverConfig[Config_Environment]["listenon"].(string)
	runtime.GOMAXPROCS(serverConfig[Config_Environment]["gomaxprocs"].(int))

	log.Printf("Starting listener at %s...", addr)

	listener, err := net.Listen("tcp", addr)
	if err != nil {
		log.Panicf("Error starting listener: %s", err)
	}

	handler := &AuthHandler{goweb.DefaultHttpHandler()}

	if useFcgi {
		log.Print("Starting in FCGI mode.")
		err = fcgi.Serve(listener, handler)
	} else {
		log.Print("Starting in HTTP mode.")
		err = http.Serve(listener, handler)
	}

	if err != nil {
		log.Panicf("Error starting server mode: %s", err)
	}

	log.Print("Starting signal handler...")

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			log.Print("Stopping the server...")
			listener.Close()

			log.Print("Cleaning up remaining tasks...")

			// FIXME cleanup
			os.Exit(0)
		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s", s.Serve(listener))

}
Exemplo n.º 14
0
func main() {

	// setup the providers
	gomniauth.SetSecurityKey("yLiCQYG7CAflDavqGH461IO0MHp7TEbpg6TwHBWdJzNwYod1i5ZTbrIF5bEoO3oP") // NOTE: DO NOT COPY THIS - MAKE YOR OWN!
	gomniauth.WithProviders(
		github.New("3d1e6ba69036e0624b61", "7e8938928d802e7582908a5eadaaaf22d64babf1", "http://localhost:8080/auth/github/callback"),
		google.New("1051709296778.apps.googleusercontent.com", "7oZxBGwpCI3UgFMgCq80Kx94", "http://localhost:8080/auth/google/callback"),
		facebook.New("537611606322077", "f9f4d77b3d3f4f5775369f5c9f88f65e", "http://localhost:8080/auth/facebook/callback"),
		uber.New("UBERKEY", "UBERSECRET", "http://localhost:8080/auth/uber/callback"),
	)

	goweb.Map("/", func(ctx context.Context) error {

		return goweb.Respond.With(ctx, http.StatusOK, []byte(`
      <html>
        <body>
          <h2>Log in with...</h2>
          <ul>
            <li>
              <a href="auth/github/login">GitHub</a>
            </li>
            <li>
              <a href="auth/google/login">Google</a>
            </li>
            <li>
              <a href="auth/facebook/login">Facebook</a>
            </li>
             <li>
              <a href="auth/uber/login">Uber</a>
            </li>
          </ul>
        </body>
      </html>
    `))

	})

	/*
	   GET /auth/{provider}/login

	   Redirects them to the fmtin page for the specified provider.
	*/
	goweb.Map("auth/{provider}/login", func(ctx context.Context) error {

		provider, err := gomniauth.Provider(ctx.PathValue("provider"))

		if err != nil {
			return err
		}

		state := gomniauth.NewState("after", "success")

		// if you want to request additional scopes from the provider,
		// pass them as login?scope=scope1,scope2
		//options := objx.MSI("scope", ctx.QueryValue("scope"))

		authUrl, err := provider.GetBeginAuthURL(state, nil)

		if err != nil {
			return err
		}

		// redirect
		return goweb.Respond.WithRedirect(ctx, authUrl)

	})

	goweb.Map("auth/{provider}/callback", func(ctx context.Context) error {

		provider, err := gomniauth.Provider(ctx.PathValue("provider"))

		if err != nil {
			return err
		}

		creds, err := provider.CompleteAuth(ctx.QueryParams())

		if err != nil {
			return err
		}

		/*
			// get the state
			state, stateErr := gomniauth.StateFromParam(ctx.QueryValue("state"))

			if stateErr != nil {
				return stateErr
			}

			// redirect to the 'after' URL
			afterUrl := state.GetStringOrDefault("after", "error?e=No after parameter was set in the state")

		*/

		// load the user
		user, userErr := provider.GetUser(creds)

		if userErr != nil {
			return userErr
		}

		return goweb.API.RespondWithData(ctx, user)

		// redirect
		//return goweb.Respond.WithRedirect(ctx, afterUrl)

	})

	/*
	   ----------------------------------------------------------------
	   START OF WEB SERVER CODE
	   ----------------------------------------------------------------
	*/

	log.Println("Starting...")
	fmt.Print("Gomniauth - Example web app\n")
	fmt.Print("by Mat Ryer and Tyler Bunnell\n")
	fmt.Print(" \n")
	fmt.Print("Starting Goweb powered server...\n")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	fmt.Printf("  visit: %s\n", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	fmt.Println("\n")
	fmt.Println("Try some of these routes:\n")
	fmt.Printf("%s", goweb.DefaultHttpHandler())
	fmt.Println("\n\n")

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			fmt.Print("Stopping the server...\n")
			listener.Close()

			/*
			   Tidy up and tear down
			*/
			fmt.Print("Tearing down...\n")

			// TODO: tidy code up here

			log.Fatal("Finished - bye bye.  ;-)\n")

		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s\n", s.Serve(listener))

	/*
	   ----------------------------------------------------------------
	   END OF WEB SERVER CODE
	   ----------------------------------------------------------------
	*/

}
Exemplo n.º 15
0
func main() {

	// map the routes
	mapRoutes()

	/*

	   START OF WEB SERVER CODE
	   This code is taken from Goweb server by Mat Ryer and Tyler Bunnell

	*/

	log.Print("Goweb 2")
	log.Print("by Mat Ryer and Tyler Bunnell")
	log.Print(" ")
	log.Print("Starting Goweb powered server...")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	log.Printf("  visit: %s", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	log.Println("")
	log.Print("Point your browser to:")
	log.Printf("\t  http://localhost%s", Address)

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			log.Print("Stopping the server...")
			listener.Close()

			log.Print("Tearing down...")
			log.Fatal("Finished - bye bye.  ;-)")

		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s", s.Serve(listener))

	/*

	   END OF WEB SERVER CODE

	*/
}
Exemplo n.º 16
0
func init() {
	api.MapRoutes()
	http.Handle("/", goweb.DefaultHttpHandler())
}
Exemplo n.º 17
0
func Controller_Project() {

	goweb.Map("/", func(c context.Context) error {

		return goweb.API.RespondWithData(c, goweb.DefaultHttpHandler().String())

	})

	// Map main projects view
	goweb.Map(gowebhttp.MethodGet, "/projects", func(c context.Context) error {
		list, err := Model_GetProjectList()

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		jsonresp, err := json.MarshalIndent(list, "", "\t")

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		return goweb.API.RespondWithData(c, jsonresp)
	})

	goweb.Map(gowebhttp.MethodGet, "/projects/user", func(c context.Context) error {
		list, err := Model_GetProjectList()

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		jsonresp, err := json.MarshalIndent(list, "", "\t")

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		return goweb.API.RespondWithData(c, jsonresp)
	})

	goweb.Map(gowebhttp.MethodGet, "/project/{name}", func(c context.Context) error {
		proj, err := Model_GetProject(c.PathParam("name"))

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		jsonresp, err := json.MarshalIndent(proj, "", "\t")

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		return goweb.API.RespondWithData(c, jsonresp)
	})

	goweb.Map("/project/{name}", func(c context.Context) error {
		proj, err := Model_GetProject(c.PathParam("name"))

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		jsonresp, err := json.MarshalIndent(proj, "", "\t")

		if err != nil {
			log.Printf("error in controller: %s", err.Error())
			debug.PrintStack()
			return goweb.API.RespondWithError(c, http.StatusInternalServerError, err.Error())
		}

		return goweb.API.RespondWithData(c, jsonresp)
	})

}
Exemplo n.º 18
0
func main() {

	// map the routes
	mapRoutes()

	/*

	   START OF WEB SERVER CODE

	*/

	log.Print("Goweb 2")
	log.Print("by Mat Ryer and Tyler Bunnell")
	log.Print(" ")
	log.Print("Starting Goweb powered server...")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	log.Printf("  visit: %s", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	log.Println("")
	log.Print("Some things to try in your browser:")
	log.Printf("\t  http://localhost%s", Address)
	log.Printf("\t  http://localhost%s/status-code/404", Address)
	log.Printf("\t  http://localhost%s/people", Address)
	log.Printf("\t  http://localhost%s/people/123", Address)
	log.Printf("\t  http://localhost%s/people/anything", Address)
	log.Printf("\t  http://localhost%s/people/me (will redirect)", Address)
	log.Printf("\t  http://localhost%s/errortest", Address)
	log.Printf("\t  http://localhost%s/things (try RESTful actions)", Address)
	log.Printf("\t  http://localhost%s/123", Address)

	log.Println("")
	log.Println("Also try some of these routes:")
	log.Printf("%s", goweb.DefaultHttpHandler())

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			log.Print("Stopping the server...")
			listener.Close()

			log.Print("Tearing down...")
			log.Fatal("Finished - bye bye.  ;-)")

		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s", s.Serve(listener))

	/*

	   END OF WEB SERVER CODE

	*/

}
Exemplo n.º 19
0
func main() {
	pins := SetupIo()

	goweb.MapStatic("/static", "static")

	// this one needs to fail if the hardware is broken in
	// any way that we can determine, though I'm not sure
	// what that will mean on rpi
	goweb.MapStaticFile("/", "index.html")

	goweb.Map("GET", "/status", func(c context.Context) error {
		jsonEncode := json.NewEncoder(c.HttpResponseWriter())
		jsonEncode.Encode(map[string]interface{}{
			"motion":     pins.GetMotion(),
			"switch1":    pins.GetSwitch("1"),
			"switch2":    pins.GetSwitch("2"),
			"switch3":    pins.GetSwitch("3"),
			"doorClosed": pins.GetDoor(),
			"led":        pins.LastOutLed,
			"strike":     pins.LastOutStrike,
		})
		return nil
	})

	goweb.Map("GET", "/trig", func(c context.Context) error {
		statements := make(chan *goraptor.Statement, 100)
		close(statements)
		serializer := goraptor.NewSerializer("trig")
		defer serializer.Free()

		str, err := serializer.Serialize(statements, "")
		if err != nil {
			panic(err)
		}
		return goweb.Respond.With(c, 200, []byte(str))
	})

	goweb.Map("GET", "/graph", func(c context.Context) error {
		DC := namespace("http://purl.org/dc/terms/")
		ROOM := namespace("http://projects.bigasterisk.com/room/")

		statements := make(chan *goraptor.Statement, 100)

		graph := ROOM("laundryDoor")

		_, thisFile, _, _ := runtime.Caller(0)
		statements <- &(goraptor.Statement{
			graph, DC("creator"), literal(thisFile, nil), graph})
		statements <- &(goraptor.Statement{
			graph, DC("modified"), nowLiteral(), graph})

		for subj, state := range map[*goraptor.Uri]*goraptor.Uri{
			ROOM("laundryDoorMotion"):  ROOM(pins.GetMotion()),
			ROOM("laundryDoorOpen"):    ROOM(pins.GetDoor()),
			ROOM("laundryDoorSwitch1"): ROOM(pins.GetSwitch("1")),
			ROOM("laundryDoorSwitch2"): ROOM(pins.GetSwitch("2")),
			ROOM("laundryDoorSwitch3"): ROOM(pins.GetSwitch("3")),
			ROOM("laundryDoorLed"):     ROOM(pins.GetLed()),
			ROOM("laundryDoorStrike"):  ROOM(pins.GetStrike()),
		} {
			statements <- &(goraptor.Statement{subj, ROOM("state"), state, graph})
		}

		close(statements)
		return serializeGowebResponse(c, "nquads", statements)
	})

	goweb.Map("PUT", "/led", func(c context.Context) error {
		body, err := c.RequestBody()
		if err != nil {
			panic(err)
		}

		pins.SetLed(string(body))
		return goweb.Respond.WithStatusText(c, http.StatusAccepted)
	})

	goweb.Map("PUT", "/strike", func(c context.Context) error {
		body, err := c.RequestBody()
		if err != nil {
			panic(err)
		}

		pins.SetStrike(string(body))
		return goweb.Respond.WithStatusText(c, http.StatusAccepted)
	})

	goweb.Map(
		"PUT", "/strike/temporaryUnlock",
		func(c context.Context) error {
			type TemporaryUnlockRequest struct {
				Seconds float64
			}

			var req TemporaryUnlockRequest
			err := json.NewDecoder(c.HttpRequest().Body).
				Decode(&req)
			if err != nil {
				panic(err)
			}

			// This is not correctly reentrant. There should be a
			// stack of temporary effects that unpop correctly,
			// and status should show you any running effects.
			pins.SetStrike("unlocked")
			go func() {
				time.Sleep(time.Duration(req.Seconds *
					float64(time.Second)))
				pins.SetStrike("locked")
			}()
			return goweb.Respond.WithStatusText(
				c, http.StatusAccepted)
		})

	goweb.Map("PUT", "/speaker/beep", func(c context.Context) error {
		// queue a beep
		return goweb.Respond.WithStatusText(c, http.StatusAccepted)
	})

	// start input posting loop. add nquads to reasoning2

	address := ":8081"

	s := &http.Server{
		Addr:         address,
		Handler:      goweb.DefaultHttpHandler(),
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	log.Printf("Listening on port %s", address)
	log.Printf("%s", goweb.DefaultHttpHandler())
	listener, listenErr := net.Listen("tcp", address)
	if listenErr != nil {
		panic(listenErr)
	}
	s.Serve(listener)
}
Exemplo n.º 20
0
func main() {

	// map the routes
	mapRoutes()

	/*
	   START OF WEB SERVER CODE
	*/

	log.Print("Webgit 1.0")
	log.Print("by Gustavo Decarlo")
	log.Print(" ")
	log.Print("Starting server...")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	log.Printf("  visit: %s", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	log.Println("")
	log.Print("Some things to try in your browser:")
	log.Printf("\t  http://localhost%s", Address)
	log.Printf("\t  http://localhost%s/status-code/404", Address)
	log.Printf("\t  http://localhost%s/gitsearch", Address)
	log.Printf("\t  http://localhost%s/reposdeveloper", Address)
	log.Printf("\t  http://localhost%s/followersdevelopers", Address)
	log.Printf("\t  http://localhost%s/developers (try RESTful actions)", Address)

	log.Println("")
	log.Println("Also try some of these routes:")
	log.Printf("%s", goweb.DefaultHttpHandler())

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			log.Print("Stopping the server...")
			listener.Close()

			/*
			   Tidy up and tear down
			*/
			log.Print("Tearing down...")

			// TODO: tidy code up here

			log.Fatal("Finished - bye bye.  ;-)")

		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s", s.Serve(listener))

	/*
	   END OF WEB SERVER CODE
	*/

}
Exemplo n.º 21
0
func main() {

	// handle every path
	goweb.Map("***", func(c context.Context) error {

		method := c.HttpRequest().Method
		requestUrl := absoluteUrlForRequest(c.HttpRequest())
		privateKey := "PRIVATE"
		body, bodyErr := ioutil.ReadAll(c.HttpRequest().Body)

		fmt.Printf("URL: %s", requestUrl)

		if bodyErr != nil {
			goweb.Respond.With(c, 500, []byte(fmt.Sprintf("Balls! Couldn't read the body because %s", bodyErr)))
			return nil
		}

		t := tracer.New(tracer.LevelEverything)

		valid, _ := signature.ValidateSignatureWithTrace(method, requestUrl, string(body), privateKey, t)

		// return the tracing
		c.HttpResponseWriter().Header().Set("Content Type", "text/html")
		c.HttpResponseWriter().Write([]byte("<html>"))
		c.HttpResponseWriter().Write([]byte("<head>"))
		c.HttpResponseWriter().Write([]byte("<title>Signature</title>"))

		c.HttpResponseWriter().Write([]byte("<link href='http://reset5.googlecode.com/hg/reset.min.css' rel='stylesheet' />"))

		c.HttpResponseWriter().Write([]byte("<style>"))
		c.HttpResponseWriter().Write([]byte(".page{padding:10px}"))
		c.HttpResponseWriter().Write([]byte(".status{padding:10px}"))

		if valid {
			c.HttpResponseWriter().Write([]byte(".status{background-color:green}"))
		} else {
			c.HttpResponseWriter().Write([]byte(".status{background-color:red}"))
		}
		c.HttpResponseWriter().Write([]byte("</style>"))

		c.HttpResponseWriter().Write([]byte("</head>"))
		c.HttpResponseWriter().Write([]byte("<body>"))
		c.HttpResponseWriter().Write([]byte("<div class='page'>"))
		c.HttpResponseWriter().Write([]byte("<div class='status'></div>"))
		c.HttpResponseWriter().Write([]byte("<pre>"))

		for _, trace := range t.Data() {
			c.HttpResponseWriter().Write([]byte(trace.Data))
			c.HttpResponseWriter().Write([]byte("\n"))
		}

		c.HttpResponseWriter().Write([]byte("</pre>"))
		c.HttpResponseWriter().Write([]byte("</div>"))

		c.HttpResponseWriter().Write([]byte("</body>"))
		c.HttpResponseWriter().Write([]byte("</html>"))

		return nil

	})

	fmt.Println("Signature test webserver")
	fmt.Println("by Mat Ryer and Tyler Bunnell")
	fmt.Println(" ")
	fmt.Println("Start making signed request to: http://localhost:8080/")

	/*

	   START OF WEB SERVER CODE

	*/

	log.Print("Goweb 2")
	log.Print("by Mat Ryer and Tyler Bunnell")
	log.Print(" ")
	log.Print("Starting Goweb powered server...")

	// make a http server using the goweb.DefaultHttpHandler()
	s := &http.Server{
		Addr:           "Address",
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	log.Printf("  visit: %s", Address)

	if listenErr != nil {
		log.Fatalf("Could not listen: %s", listenErr)
	}

	log.Println("Also try some of these routes:")
	log.Printf("%s", goweb.DefaultHttpHandler())

	go func() {
		for _ = range c {

			// sig is a ^C, handle it

			// stop the HTTP server
			log.Print("Stopping the server...")
			listener.Close()

			/*
			   Tidy up and tear down
			*/
			log.Print("Tearing down...")

			// TODO: tidy code up here

			log.Fatal("Finished - bye bye.  ;-)")

		}
	}()

	// begin the server
	log.Fatalf("Error in Serve: %s", s.Serve(listener))

	/*

	   END OF WEB SERVER CODE

	*/

}
Exemplo n.º 22
0
func main() {
	// init(s)
	conf.Initialize()
	logger.Initialize()
	if err := db.Initialize(); err != nil {
		logger.Error(err.Error())
	}
	user.Initialize()
	node.Initialize()
	preauth.Initialize()
	auth.Initialize()

	// print conf
	printLogo()
	conf.Print()

	if _, err := os.Stat(conf.Conf["data-path"] + "/temp"); err != nil && os.IsNotExist(err) {
		if err := os.Mkdir(conf.Conf["data-path"]+"/temp", 0777); err != nil {
			fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
			logger.Error("ERROR: " + err.Error())
		}
	}

	// reload
	if conf.RELOAD != "" {
		fmt.Println("####### Reloading #######")
		err := reload(conf.RELOAD)
		if err != nil {
			fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
			logger.Error("ERROR: " + err.Error())
		}
		fmt.Println("Done")
	}

	// setting GOMAXPROCS
	var procs int
	avail := runtime.NumCPU()
	if avail <= 2 {
		procs = 1
	} else if avail == 3 {
		procs = 2
	} else {
		procs = avail - 2
	}

	fmt.Println("##### Procs #####")
	fmt.Printf("Number of available CPUs = %d\n", avail)
	if conf.Conf["GOMAXPROCS"] != "" {
		if setting, err := strconv.Atoi(conf.Conf["GOMAXPROCS"]); err != nil {
			fmt.Fprintf(os.Stderr, "ERROR: could not interpret configured GOMAXPROCS value as integer.")
		} else {
			procs = setting
		}
	}

	if procs <= avail {
		fmt.Printf("Running Shock server with GOMAXPROCS = %d\n", procs)
		runtime.GOMAXPROCS(procs)
	} else {
		fmt.Println("GOMAXPROCS config value is greater than available number of CPUs.")
		fmt.Printf("Running Shock server with GOMAXPROCS = %d\n", avail)
		runtime.GOMAXPROCS(avail)
	}

	Address := ":" + conf.Conf["api-port"]
	mapRoutes()

	s := &http.Server{
		Addr:           ":" + Address,
		Handler:        goweb.DefaultHttpHandler(),
		ReadTimeout:    100 * time.Second,
		WriteTimeout:   100 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	listener, listenErr := net.Listen("tcp", Address)

	if listenErr != nil {
		fmt.Fprintf(os.Stderr, "Could not listen: %s\n", listenErr)
	}

	go func() {
		for _ = range c {
			// sig is a ^C, handle it

			// stop the HTTP server
			fmt.Fprintln(os.Stderr, "Stopping the server...")
			listener.Close()
		}
	}()

	fmt.Fprintf(os.Stderr, "Error in Serve: %s\n", s.Serve(listener))
}