Beispiel #1
0
func runAPI(wg *sync.WaitGroup) {
	mux := goji.NewMux()

	// List all webhooks
	mux.HandleFuncC(
		pat.Get("/webhooks"),
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			ui := uhttp.UI{ctx, r, w}
			kase := usecase.ListWebhooks{
				DB:  &drivers.DB,
				Out: &ui,
			}

			if err := kase.Exec(); err != nil {
				fail(err)
			}
		},
	)

	// Create a new webhook
	mux.HandleFuncC(
		pat.Post("/webhooks"),
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) {},
	)

	// Delete a webhook
	mux.HandleFuncC(
		pat.Delete("/webhooks/:id"),
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) {},
	)

	http.ListenAndServe("localhost:8000", mux)
	wg.Done()
}
Beispiel #2
0
func Listen() {
	mux := goji.NewMux()
	mux.HandleFunc(pat.Post("/reset.json"), reset)
	mux.HandleFuncC(pat.Get("/:name.json"), show)
	mux.HandleFunc(pat.Get("/"), index)

	bind := fmt.Sprintf(":%s", getBindPort())
	log.Fatal(http.ListenAndServe(bind, mux))
}
// Post registers a `POST /resource` handler with the resource
func (res *Resource) Post(storage store.Save) {
	res.HandleFuncC(
		pat.Post(patRoot),
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			res.postHandler(ctx, w, r, storage)
		},
	)

	res.addRoute(post, patRoot)
}
Beispiel #4
0
func main() {
	mux := goji.NewMux()
	// mux.HandleFuncC(pat.Get("/hello/:name"), hello)
	mux.HandleFuncC(pat.Post("/view"), view)
	// mux.HandleFuncC(pat.Post("/details"), details)

	mux.Use(JSONContentTypeMiddleware)

	http.ListenAndServe("0.0.0.0:8004", mux)

}
Beispiel #5
0
func main() {
	session, err := mgo.Dial("localhost")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	ensureIndex(session)

	mux := goji.NewMux()
	mux.HandleFuncC(pat.Get("/books"), allBooks(session))
	mux.HandleFuncC(pat.Post("/books"), addBook(session))
	mux.HandleFuncC(pat.Get("/books/:isbn"), bookByISBN(session))
	mux.HandleFuncC(pat.Put("/books/:isbn"), updateBook(session))
	mux.HandleFuncC(pat.Delete("/books/:isbn"), deleteBook(session))
	http.ListenAndServe("localhost:8080", mux)
}
Beispiel #6
0
func API() *goji.Mux {
	mux := goji.SubMux()

	// We pass the routes as relative to the point where the API router
	// will be mounted.  The super-router will strip any prefix off for us.
	mux.HandleFuncC(pat.Get("/people"), api.ListPeople)
	mux.HandleFuncC(pat.Post("/people"), api.CreatePerson)
	mux.HandleFuncC(pat.Get("/people/:person"), api.GetPerson)
	mux.HandleFuncC(pat.Delete("/people/:person"), api.DeletePerson)

	// Add default 'not found' route that responds with JSON
	mux.HandleFunc(pat.New("/*"), func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(404)
		fmt.Fprint(w, `{"error":"not found"}`)
	})

	return mux
}
Beispiel #7
0
// BuildServer creates a new HTTP Server
func BuildServer(debug bool) *jshapi.API {

	// setup logging
	logger := buildLogger()
	jshapi.Logger = logger

	api := jshapi.New("", debug)

	// set middleware
	api.Use(buildCORS(debug).Handler)

	// /users Routes
	userAPI := &UserAPI{Logger: logger}
	users := jshapi.NewCRUDResource("users", userAPI)
	api.Add(users)
	api.Mux.HandleFuncC(pat.Post("/register"), userAPI.Register)

	return api
}
Beispiel #8
0
	DBMaxOpen int    // maximum number of open DB connections

	IPPerMinute int // maximum number of requests per IP per minute
	IPRateBurst int // maximum burst of requests from an IP

	UserSecret []byte // secret for generating secure user tokens
}

var Routes = struct {
	CreateUser, GetUser,
	GetAnimals,
	ListMoods, SetMood, GetMood, DeleteMood,
	ListConversations, CreateConversation, GetConversation, DeleteConversation,
	CreateLine, GetLine, DeleteLine *pat.Pattern
}{
	CreateUser: pat.Post("/users"),
	GetUser:    pat.Get("/users/:id"),

	GetAnimals: pat.Get("/animals"),

	ListMoods:  pat.Get("/moods"),
	SetMood:    pat.Put("/moods/:mood"),
	GetMood:    pat.Get("/moods/:mood"),
	DeleteMood: pat.Delete("/moods/:mood"),

	ListConversations:  pat.Get("/conversations"),
	CreateConversation: pat.Post("/conversations"),
	GetConversation:    pat.Get("/conversations/:conversation"),
	DeleteConversation: pat.Delete("/conversations/:conversation"),

	CreateLine: pat.Post("/conversations/:conversation/lines"),
Beispiel #9
0
// New creates an App for the given configuration.
func New(config *Configuration) (*App, error) {
	var app App

	db, err := buildDB(config.DBDSN, config.DBMaxIdle, config.DBMaxOpen)
	if err != nil {
		defer app.Close()
		return nil, err
	}
	app.closers = append(app.closers, db)

	ipQuota := throttled.RateQuota{throttled.PerMin(config.IPPerMinute), config.IPRateBurst}
	ipLimiter, err := buildLimiter(ipQuota)

	authCtrl, err := auth.New(config.UserSecret)
	if err != nil {
		defer app.Close()
		return nil, err
	}

	sayCtrl, err := say.New(db)
	if err != nil {
		defer app.Close()
		return nil, err
	}
	app.closers = append(app.closers, sayCtrl)

	// TODO: Proper not found handler
	privMux := goji.NewMux()
	privMux.UseC(metrics.WrapSubmuxC)
	privMux.UseC(authCtrl.WrapC)

	privMux.HandleFuncC(Routes.GetAnimals, sayCtrl.GetAnimals)

	privMux.HandleFuncC(Routes.ListMoods, sayCtrl.ListMoods)
	privMux.HandleFuncC(Routes.SetMood, sayCtrl.SetMood)
	privMux.HandleFuncC(Routes.GetMood, sayCtrl.GetMood)
	privMux.HandleFuncC(Routes.DeleteMood, sayCtrl.DeleteMood)

	privMux.HandleFuncC(pat.Get("/conversations"), sayCtrl.ListConversations)
	privMux.HandleFuncC(pat.Post("/conversations"), sayCtrl.CreateConversation)
	privMux.HandleFuncC(pat.Get("/conversations/:conversation"), sayCtrl.GetConversation)
	privMux.HandleFuncC(pat.Delete("/conversations/:conversation"), sayCtrl.DeleteConversation)

	privMux.HandleFuncC(pat.Post("/conversations/:conversation/lines"), sayCtrl.CreateLine)
	privMux.HandleFuncC(pat.Get("/conversations/:conversation/lines/:line"), sayCtrl.GetLine)
	privMux.HandleFuncC(pat.Delete("/conversations/:conversation/lines/:line"), sayCtrl.DeleteLine)

	mainMux := goji.NewMux()
	mainMux.HandleFuncC(Routes.CreateUser, authCtrl.CreateUser)
	mainMux.HandleFuncC(Routes.GetUser, authCtrl.GetUser)
	mainMux.HandleC(pat.New("/*"), privMux)

	mainMux.UseC(reqlog.WrapC)
	mainMux.UseC(respond.WrapPanicC)
	mainMux.UseC(metrics.WrapC)
	mainMux.Use(ipLimiter.RateLimit)

	app.srv = mainMux

	return &app, nil
}
Beispiel #10
0
	DBDSN     string // postgres data source name
	DBMaxIdle int    // maximum number of idle DB connections
	DBMaxOpen int    // maximum number of open DB connections

	IPPerMinute int // maximum number of requests per IP per minute
	IPRateBurst int // maximum burst of requests from an IP

	UserSecret []byte // secret for generating secure user tokens
}

var Routes = struct {
	CreateUser, GetUser,
	GetAnimals,
	ListMoods, SetMood, GetMood, DeleteMood *pat.Pattern
}{
	CreateUser: pat.Post("/users"),
	GetUser:    pat.Get("/users/:id"),

	GetAnimals: pat.Get("/animals"),

	ListMoods:  pat.Get("/moods"),
	SetMood:    pat.Put("/moods/:mood"),
	GetMood:    pat.Get("/moods/:mood"),
	DeleteMood: pat.Delete("/moods/:mood"),
}

// App encapsulates the handlers for the saypi API
type App struct {
	srv     http.Handler
	closers []io.Closer
}
Beispiel #11
0
func (m *Mux) Post(pattern string, handler goji.Handler, doc *Doc) {
	muxMap(m, "post", pattern, handler, doc)
	m.webmux.HandleC(pat.Post(pattern), handler)
}
Beispiel #12
0
func main() {
	klog.Info("starting kahinah v4")

	// -- mux -----------------------------------------------------------------
	mux := goji.NewMux()

	// -- middleware ----------------------------------------------------------

	// logging middleware (base middleware)
	mux.UseC(func(inner goji.Handler) goji.Handler {
		return goji.HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
			klog.Debugf("req  (%v): path (%v), user-agent (%v), referrer (%v)", r.RemoteAddr, r.RequestURI, r.UserAgent(), r.Referer())
			wp := mutil.WrapWriter(rw) // proxy the rw for info later
			inner.ServeHTTPC(ctx, wp, r)
			klog.Debugf("resp (%v): status (%v), bytes written (%v)", r.RemoteAddr, wp.Status(), wp.BytesWritten())
		})
	})

	// rendering middleware (required by panic)
	renderer := urender.New(urender.Options{
		Directory:  "views",
		Layout:     "layout",
		Extensions: []string{".tmpl", ".tpl"},
		Funcs: []template.FuncMap{
			template.FuncMap{
				"rfc3339": func(t time.Time) string {
					return t.Format(time.RFC3339)
				},
				"since": func(t time.Time) string {
					hrs := time.Since(t).Hours()
					return fmt.Sprintf("%dd %02dhrs", int(hrs)/24, int(hrs)%24)
				},
				"emailat": func(s string) string {
					return strings.Replace(s, "@", " [@T] ", -1)
				},
				"mapaccess": func(s interface{}, m map[string]string) string {
					return m[to.String(s)]
				},
				"url":     render.ConvertURL,
				"urldata": render.ConvertURLWithData,
			},
		},
		IndentJSON:    true,
		IndentXML:     true,
		IsDevelopment: conf.GetDefault("runMode", "dev").(string) == "dev",
	})

	mux.UseC(func(inner goji.Handler) goji.Handler {
		return goji.HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
			newCtx := render.NewContext(ctx, renderer)
			inner.ServeHTTPC(newCtx, rw, r)
		})
	})

	// panic middleware
	mux.UseC(controllers.PanicMiddleware)

	// not found middleware
	mux.UseC(func(inner goji.Handler) goji.Handler {
		return goji.HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
			routeFound := middleware.Pattern(ctx)

			if routeFound != nil {
				inner.ServeHTTPC(ctx, rw, r)
				return
			}

			panic(controllers.ErrNotFound)
		})
	})

	// authentication (cas) middleware
	if enable, ok := conf.GetDefault("authentication.cas.enable", false).(bool); ok && enable {
		url, _ := url.Parse(conf.Get("authentication.cas.url").(string))

		casClient := cas.NewClient(&cas.Options{
			URL: url,
		})

		mux.Use(casClient.Handle)
	}

	// sessions middleware
	sessionConfig := &sessionmw.Config{
		Secret:      []byte(securecookie.GenerateRandomKey(64)),
		BlockSecret: []byte(securecookie.GenerateRandomKey(32)),
		Store:       kv.NewMemStore(),
		Name:        "kahinah",
	}
	mux.UseC(sessionConfig.Handler)

	// csrf middleware
	mux.UseC(csrf.Protect(securecookie.GenerateRandomKey(64), csrf.Secure(false)))

	// data rendering middleware
	mux.UseC(func(inner goji.Handler) goji.Handler {
		return goji.HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
			newCtx := data.RenderMiddleware(ctx, rw, r)
			inner.ServeHTTPC(newCtx, rw, r)
			data.RenderAfterware(newCtx, rw, r)
		})
	})

	// --------------------------------------------------------------------
	// HANDLERS
	// --------------------------------------------------------------------

	getHandlers := map[string]goji.HandlerFunc{

		// static paths
		"/static/*": controllers.StaticHandler,

		// main page
		"/": controllers.MainHandler,

		// builds - json
		"/i/list/json/": controllers.ListsAPIHandler,

		// builds
		"/i/list/": controllers.ListsHandler,

		// build - specific
		"/b/:id/": controllers.BuildGetHandler,

		// build - specific - json
		"/b/:id/json/": controllers.BuildGetJSONHandler,

		// activity - json
		"/i/activity/json/": controllers.ActivityJSONHandler,

		// activity - html
		"/i/activity/": controllers.ActivityHandler,

		// admin
		"/admin/": controllers.AdminGetHandler,

		// authentication - login
		"/u/login/": controllers.UserLoginHandler,

		// authentication - logout
		"/u/logout/": controllers.UserLogoutHandler,
	}

	postHandlers := map[string]goji.HandlerFunc{

		// webhooks
		"/hook/*": controllers.IntegrationHandler,

		// build - specific
		"/b/:id/": controllers.BuildPostHandler,

		// admin
		"/admin/": controllers.AdminPostHandler,
	}

	for k, v := range getHandlers {
		if len(k) > 1 && strings.HasSuffix(k, "/") {
			getHandlerRedirectName := render.ConvertURLRelative(k[:len(k)-1])
			klog.Debugf("get handler setup: redirecting %v", getHandlerRedirectName)
			mux.HandleFunc(pat.Get(getHandlerRedirectName), controllers.RedirectHandler)
		}
		getHandlerUseName := render.ConvertURLRelative(k)
		klog.Debugf("get handler setup: using %v", getHandlerUseName)
		mux.HandleC(pat.Get(getHandlerUseName), v)
	}

	for k, v := range postHandlers {
		if len(k) > 1 && strings.HasSuffix(k, "/") {
			postHandlerRedirectName := render.ConvertURLRelative(k[:len(k)-1])
			klog.Debugf("post handler setup: redirecting %v", postHandlerRedirectName)
			mux.HandleFunc(pat.Post(postHandlerRedirectName), controllers.RedirectHandler)
		}
		postHandlerUseName := render.ConvertURLRelative(k)
		klog.Debugf("post handler setup: using %v", postHandlerUseName)
		mux.HandleC(pat.Post(postHandlerUseName), v)
	}

	// -- cronjobs ----------------------------------------------------------

	cronRunner := cron.New()

	// integration polling
	if pollRate, ok := conf.Get("integration.poll").(string); ok && pollRate != "" {
		pollFunc := func() {
			pollAllErr := integration.PollAll()
			for name, err := range pollAllErr {
				klog.Warningf("integration polling failed for %v: %v", name, err)
			}
		}
		cronRunner.AddFunc(pollRate, pollFunc)

		// and do an initial poll
		pollFunc()
	}

	// process new stages/check processes every 10 seconds
	cronRunner.AddFunc("@every 10s", func() {
		models.CheckAllListStages()
	})

	// run the job scheduler every minute
	cronRunner.AddFunc("@every 1m", func() {
		job.ProcessQueue()
	})

	// start cron
	cronRunner.Start()

	// -- server setup --------------------------------------------------------

	// bind and listen
	listenAddr := conf.GetDefault("listenAddr", "0.0.0.0").(string)
	listenPort := conf.GetDefault("listenPort", 3000).(int64)

	klog.Infof("listening to %v:%v", listenAddr, listenPort)
	if err := http.ListenAndServe(fmt.Sprintf("%v:%v", listenAddr, listenPort), mux); err != nil {
		klog.Fatalf("unable to serve: %v", err)
	}

	cronRunner.Stop()

	klog.Info("processing leftover jobs...")
	close(job.Queue)
	for len(job.Queue) > 0 {
		job.ProcessQueue()
	}
}
Beispiel #13
0
func main() {

	log.Println("localhost:4242")

	// Connection a la base de donnee
	initdatabase()
	defer database.Close()

	gob.Register(UserData{})
	gob.Register(InscriptionForm{})

	mux := goji.NewMux()

	mux.HandleFunc(pat.Get("/"), home)

	// Creation d'un compte
	mux.HandleFunc(pat.Get("/inscription"), inscription)
	mux.HandleFunc(pat.Post("/users"), postUsers)

	// Connexion Deconnexion utilisateur
	mux.HandleFunc(pat.Post("/login"), login)
	mux.HandleFunc(pat.Get("/logout"), logout)
	mux.HandleFunc(pat.Get("/me"), connectedUser)

	// User's interests Road
	mux.HandleFunc(pat.Post("/users/me/interests/"), postUsersInterests)
	mux.HandleFunc(pat.Get("/users/me/interests/"), getUsersInterests)
	mux.HandleFuncC(pat.Delete("/users/me/interests/:interestid"), deleteUsersInterests)
	// User's age Road
	mux.HandleFunc(pat.Put("/users/me/age/"), postUsersAge)
	mux.HandleFunc(pat.Get("/users/me/age/"), getUsersAge)
	// User's username Road
	mux.HandleFunc(pat.Put("/users/me/username/"), postUsersUsername)
	mux.HandleFunc(pat.Get("/users/me/username/"), getUsersUsername)
	// User's firstname Road
	mux.HandleFunc(pat.Put("/users/me/firstname/"), postUsersFirstName)
	mux.HandleFunc(pat.Get("/users/me/firstname/"), getUsersFirstName)
	// User's lastname Road
	mux.HandleFunc(pat.Put("/users/me/lastname/"), postUsersLastName)
	mux.HandleFunc(pat.Get("/users/me/lastname/"), getUsersLastName)
	// User's Bio Road
	mux.HandleFunc(pat.Put("/users/me/bio/"), uptdateUsersBio)

	// Public Profile
	mux.HandleFuncC(pat.Get("/users/:id"), publicProfile)
	mux.HandleFuncC(pat.Put("/users/:id/like/"), likeAnUser)
	mux.HandleFuncC(pat.Put("/users/:id/unlike/"), unlikeAnUser)
	// Notifications
	mux.HandleFuncC(pat.Put("/notifications/:id"), setReadNotifications)
	mux.HandleFunc(pat.Get("/notifications/"), getNotifications)

	//Matches
	mux.HandleFunc(pat.Get("/users/me/matches/"), getUsersMatches)

	// Interests
	mux.HandleFunc(pat.Post("/interests/"), postInterests)

	// Chat

	mux.HandleFuncC(pat.Get("/chat/:chatname"), RootHandler)
	mux.Handle(pat.Get("/sock"), websocket.Handler(SockServer))

	// Static Files
	mux.HandleFunc(pat.Get("/css/*"), staticCssFiles)
	mux.HandleFunc(pat.Get("/js/*"), staticJsFiles)

	log.Fatal(http.ListenAndServe(LISTEN_PORT, mux))

}