Beispiel #1
0
func mapStatics() {
	root := os.Getenv("GOPATH") + "/src/github.com/ToQoz/Gokuraku"

	goweb.MapStaticFile("/", root+"/public/html/index.html")
	goweb.MapStatic("/js", root+"/public/js")
	goweb.MapStatic("/css", root+"/public/css")
	goweb.MapStaticFile("/favicon.ico", root+"/public/favicon.ico")
	goweb.Map("/soundcloud_client_id", func(ctx context.Context) error {
		return goweb.API.RespondWithData(ctx, gokuraku.Config.SoundcloudClientId)
	})
	goweb.Map("/websocket_port", func(ctx context.Context) error {
		return goweb.API.RespondWithData(ctx, gokuraku.Config.WebSocketPort)
	})
}
Beispiel #2
0
func MapRoutes(dbSession *r.Session) {

	// before everything
	// goweb.MapBefore(func(c context.Context) error {
	// 	// authentication
	// 	c.HttpResponseWriter().Header().Set("X-Custom-Header", "Authentication")
	// 	return nil
	// })

	accounts := &controllers.Accounts{DbSession: dbSession}
	goweb.MapController(accounts)
	goweb.Map(gowebhttp.MethodPost, "/api/accounts/{id}/adjust", accounts.Adjust)

	accountTransactions := &controllers.AccountTransactions{DbSession: dbSession}
	goweb.MapController(accountTransactions)

	goweb.MapStatic("/public", "src/public")
	goweb.MapStaticFile("/", "src/index.html")
	goweb.MapStaticFile("/favicon.ico", "src/favicon.ico")

	// Catch-all handler for everything that we don't understand
	goweb.Map(func(c context.Context) error {
		// just return a 404 message
		return goweb.API.Respond(c, 404, nil, []string{"File not found"})
	})
}
Beispiel #3
0
func mapRoutes() (err error) {
	goweb.MapBefore(beforeHandler)
	goweb.MapAfter(afterHandler)

	// static files
	goweb.MapStatic("/", *flagDirPath, func(c context.Context) (handlers.MatcherFuncDecision, error) {
		if regexp.MustCompile(`^api`).MatchString(c.Path().RawPath) {
			return handlers.NoMatch, nil
		}
		return handlers.Match, nil
	})

	// apis
	goweb.MapController("/api/session", &SessionController{})
	goweb.MapController("/api/statuses", &StatusesController{})
	goweb.MapController("/api/user", &UserController{})
	goweb.MapController("/api/search", &SearchController{})
	goweb.MapController("/api/token", &TokenController{})

	return nil
}
Beispiel #4
0
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())
}
Beispiel #5
0
func MapStaticFiles() {
	goweb.MapStatic("/js", settings.ProjectPath+"/public/js")
	goweb.MapStatic("/less", settings.ProjectPath+"/public/less")
	goweb.MapStatic("/partials", settings.ProjectPath+"/public/partials")
	goweb.MapStaticFile("***", settings.ProjectPath+"/public/app.html")
}
Beispiel #6
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)
}
Beispiel #7
0
// mapRoutes contains lots of examples of how to map things in
// Goweb.  It is in its own function so that test code can call it
// without having to run main().
func mapRoutes() {

	/*
		Add a pre-handler to save the referrer
	*/
	goweb.MapBefore(func(c context.Context) error {

		// add a custom header
		c.HttpResponseWriter().Header().Set("X-Custom-Header", "Goweb")

		return nil
	})

	/*
		Add a post-handler to log something
	*/
	goweb.MapAfter(func(c context.Context) error {
		// TODO: log this
		return nil
	})

	/*
		Map the homepage...
	*/
	goweb.Map("/", func(c context.Context) error {
		return goweb.Respond.With(c, 200, []byte("Welcome to the Goweb example app - see the terminal for instructions."))
	})

	/*
		Map a specific route that will redirect
	*/
	goweb.Map("GET", "people/me", func(c context.Context) error {
		hostname, _ := os.Hostname()
		return goweb.Respond.WithRedirect(c, fmt.Sprintf("/people/%s", hostname))
	})

	/*
		/people (with optional ID)
	*/
	goweb.Map("GET", "people/[id]", func(c context.Context) error {

		if c.PathParams().Has("id") {
			return goweb.API.Respond(c, 200, fmt.Sprintf("Yes, this worked and your ID is %s", c.PathParams().Get("id")), nil)
		} else {
			return goweb.API.Respond(c, 200, "Yes, this worked but you didn't specify an ID", nil)
		}

	})

	/*
		/status-code/xxx
		Where xxx is any HTTP status code.
	*/
	goweb.Map("/status-code/{code}", func(c context.Context) error {

		// get the path value as an integer
		statusCodeInt, statusCodeIntErr := strconv.Atoi(c.PathValue("code"))
		if statusCodeIntErr != nil {
			return goweb.Respond.With(c, http.StatusInternalServerError, []byte("Failed to convert 'code' into a real status code number."))
		}

		// respond with the status
		return goweb.Respond.WithStatusText(c, statusCodeInt)
	})

	// /errortest should throw a system error and be handled by the
	// DefaultHttpHandler().ErrorHandler() Handler.
	goweb.Map("/errortest", func(c context.Context) error {
		return errors.New("This is a test error!")
	})

	/*
		Map a RESTful controller
		(see the ThingsController for all the methods that will get
		 mapped)
	*/
	thingsController := new(ThingsController)
	goweb.MapController(thingsController)

	/*
		Map a handler for if they hit just numbers using the goweb.RegexPath
		function.

		e.g. GET /2468

		NOTE: The goweb.RegexPath is a MatcherFunc, and so comes _after_ the
		      handler.
	*/
	goweb.Map(func(c context.Context) error {
		return goweb.API.RespondWithData(c, "Just a number!")
	}, goweb.RegexPath(`^[0-9]+$`))

	/*
		Map the static-files directory so it's exposed as /static
	*/
	goweb.MapStatic("/static", "static-files")

	/*
		Map the a favicon
	*/
	goweb.MapStaticFile("/favicon.ico", "static-files/favicon.ico")

	/*
		Catch-all handler for everything that we don't understand
	*/
	goweb.Map(func(c context.Context) error {

		// just return a 404 message
		return goweb.API.Respond(c, 404, nil, []string{"File not found"})

	})

}
Beispiel #8
0
// mapRoutes contains lots of examples of how to map things in
// Goweb.  It is in its own function so that test code can call it
// without having to run main().
func mapRoutes() {
	goweb.MapBefore(func(c context.Context) error {
		c.HttpResponseWriter().Header().Set("X-Custom-Header", "WebGit")
		c.HttpResponseWriter().Header().Set("Connection", "keep-alive")
		return nil
	})

	goweb.MapAfter(func(c context.Context) error {
		// TODO: log this
		return nil
	})

	/*
		Map the homepage...
	*/
	goweb.Map("/", func(c context.Context) error {
		return goweb.Respond.With(c, 200, []byte("Welcome to the WebGit app - see the terminal for instructions."))
	})

	/*
		search git developers
	*/
	goweb.Map("GET", "gitsearch", func(c context.Context) error {
		if c.QueryParams().Has("q") {
			res, err := http.Get("https://api.github.com/search/users?q=" + c.QueryValue("q"))
			if err != nil {
				log.Fatal(err)
				return goweb.API.Respond(c, 200, fmt.Sprintf("Erro: %s", err), nil)
			}
			response, err := ioutil.ReadAll(res.Body)
			res.Body.Close()
			if err != nil {
				log.Fatal(err)
				return goweb.API.Respond(c, 200, fmt.Sprintf("Erro: %s", err), nil)
			}
			return goweb.API.Respond(c, 200, fmt.Sprintf("%s", response), nil)
		} else {
			return goweb.API.Respond(c, 200, "Pesquisa vazia", nil)
		}
	})

	/*
		repo git developer
	*/
	goweb.Map("GET", "reposdeveloper", func(c context.Context) error {
		if c.QueryParams().Has("user") {
			res, err := http.Get("https://api.github.com/users/" + c.QueryValue("user") + "/repos")
			if err != nil {
				log.Fatal(err)
				return goweb.API.Respond(c, 200, fmt.Sprintf("Erro: %s", err), nil)
			}
			response, err := ioutil.ReadAll(res.Body)
			res.Body.Close()
			if err != nil {
				log.Fatal(err)
				return goweb.API.Respond(c, 200, fmt.Sprintf("Erro: %s", err), nil)
			}
			return goweb.API.Respond(c, 200, fmt.Sprintf("%s", response), nil)
		} else {
			return goweb.API.Respond(c, 200, "No user send", nil)
		}
	})

	/*
		followers git developer
	*/
	goweb.Map("GET", "followersdevelopers", func(c context.Context) error {
		if c.QueryParams().Has("user") {
			res, err := http.Get("https://api.github.com/users/" + c.QueryValue("user") + "/followers")
			if err != nil {
				log.Fatal(err)
				return goweb.API.Respond(c, 200, fmt.Sprintf("Erro: %s", err), nil)
			}
			response, err := ioutil.ReadAll(res.Body)
			res.Body.Close()
			if err != nil {
				log.Fatal(err)
				return goweb.API.Respond(c, 200, fmt.Sprintf("Erro: %s", err), nil)
			}
			return goweb.API.Respond(c, 200, fmt.Sprintf("%s", response), nil)
		} else {
			return goweb.API.Respond(c, 200, "Pesquisa vazia", nil)
		}
	})

	/*
		/status-code/xxx
		Where xxx is any HTTP status code.
	*/
	goweb.Map("/status-code/{code}", func(c context.Context) error {

		// get the path value as an integer
		statusCodeInt, statusCodeIntErr := strconv.Atoi(c.PathValue("code"))
		if statusCodeIntErr != nil {
			return goweb.Respond.With(c, http.StatusInternalServerError, []byte("Failed to convert 'code' into a real status code number."))
		}

		// respond with the status
		return goweb.Respond.WithStatusText(c, statusCodeInt)
	})

	// /errortest should throw a system error and be handled by the
	// DefaultHttpHandler().ErrorHandler() Handler.
	goweb.Map("/errortest", func(c context.Context) error {
		return errors.New("This is a test error!")
	})

	/*
		Map a RESTful controller
		(see the DevelopersController for all the methods that will get
		 mapped)
	*/
	developersController := new(DevelopersController)
	goweb.MapController(developersController)

	/*
		Map a handler for if they hit just numbers using the goweb.RegexPath
		function.
		e.g. GET /2468
		NOTE: The goweb.RegexPath is a MatcherFunc, and so comes _after_ the
		      handler.
	*/
	goweb.Map(func(c context.Context) error {
		return goweb.API.RespondWithData(c, "Just a number!")
	}, goweb.RegexPath(`^[0-9]+$`))

	/*
		Map the static-files directory so it's exposed as /static
	*/
	goweb.MapStatic("/static", "static-files")

	/*
		Map the a favicon
	*/
	goweb.MapStaticFile("/favicon.ico", "static-files/favicon.ico")

	/*
		Catch-all handler for everything that we don't understand
	*/
	goweb.Map(func(c context.Context) error {

		// just return a 404 message
		return goweb.API.Respond(c, 404, nil, []string{"File not found"})

	})
}
Beispiel #9
0
func mapRoutes() {
	goweb.MapBefore(func(ctx context.Context) error {
		req := ctx.HttpRequest()
		host, _, _ := net.SplitHostPort(req.RemoteAddr)
		if host == "::1" {
			host = "localhost"
		}
		suffix := ""
		if _, ok := req.Header["Authorization"]; ok {
			suffix += " AUTH"
		}
		if l, has := req.Header["Content-Length"]; has {
			suffix += " Content-Length: " + l[0]
		}
		logger.Info("access", fmt.Sprintf("%s REQ RECEIVED \"%s %s%s\"", host, ctx.MethodString(), req.RequestURI, suffix))
		return nil
	})

	goweb.MapAfter(func(ctx context.Context) error {
		req := ctx.HttpRequest()
		host, _, _ := net.SplitHostPort(req.RemoteAddr)
		if host == "::1" {
			host = "localhost"
		}
		suffix := ""
		if _, ok := req.Header["Authorization"]; ok {
			suffix += " AUTH"
		}
		if l, has := req.Header["Content-Length"]; has {
			suffix += " Content-Length: " + l[0]
		}
		logger.Info("access", fmt.Sprintf("RESPONDED TO %s \"%s %s%s\"", host, ctx.MethodString(), req.RequestURI, suffix))
		return nil
	})

	goweb.Map("/preauth/{id}", func(ctx context.Context) error {
		pcon.PreAuthRequest(ctx)
		return nil
	})

	goweb.Map("/node/{nid}/acl/{type}", func(ctx context.Context) error {
		acon.AclTypedRequest(ctx)
		return nil
	})

	goweb.Map("/node/{nid}/acl/", func(ctx context.Context) error {
		acon.AclRequest(ctx)
		return nil
	})

	goweb.Map("/node/{nid}/index/{idxType}", func(ctx context.Context) error {
		icon.IndexTypedRequest(ctx)
		return nil
	})

	goweb.Map("/", func(ctx context.Context) error {
		host := util.ApiUrl(ctx)
		r := resource{
			R: []string{"node"},
			U: host + "/",
			D: host + "/documentation.html",
			C: conf.Conf["admin-email"],
			I: "Shock",
			T: "Shock",
		}
		return responder.WriteResponseObject(ctx, http.StatusOK, r)
	})

	nodeController := new(ncon.NodeController)
	goweb.MapController(nodeController)

	goweb.MapStatic("/assets", conf.Conf["site-path"]+"/assets")
	goweb.MapStaticFile("/documentation.html", conf.Conf["site-path"]+"/pages/main.html")

	// Map the favicon
	//goweb.MapStaticFile("/favicon.ico", "static-files/favicon.ico")

	// Catch-all handler for everything that we don't understand
	goweb.Map(func(ctx context.Context) error {
		return responder.RespondWithError(ctx, http.StatusNotFound, "File not found")
	})
}