Example #1
0
func main() {

	var (
		redisAddress string
		router       *mux.Router
		err          error
		port         int
	)

	flag.IntVar(&port, "port", 4242, "Local port to listen on")
	flag.StringVar(&redisAddress, "redis-address", "localhost:6379", "Redis server address (host:port)")
	flag.Parse()

	if redisConn, err = redis.NewRedis(redisAddress); err != nil {
		log.Fatalf("Unable to connect to Redis server at %v\n", redisAddress)
	}
	log.Printf("Connected to Redis server at %v\n", redisAddress)

	router = mux.NewRouter()
	router.HandleFunc("/entries/{category}", GetEntries).Methods("GET")
	router.HandleFunc("/add/{category}", AddEntry).Methods("POST")
	http.Handle("/", router)

	log.Printf("Listening on http://localhost:%v\n", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
Example #2
0
func Home(r *mux.Router) {

	//home
	r.HandleFunc("/home", func(w http.ResponseWriter, req *http.Request) {
		view(w, "index", "Eu sou a mensagem exemplo")
	})
}
Example #3
0
// AddPingRoute adds an optimized ping route to the given router
func AddPingRoute(router *mux.Router) *mux.Route {
	return router.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"pong":true}`))
	}).Methods("GET", "HEAD", "OPTIONS")
}
Example #4
0
// Mount adds CRUD and OPTIONS routes to the router, which rely on the given Storage. You can provide a middleware function auth that authenticates and authorizes requests.
func Mount(router *mux.Router, storage Storage, auth func(http.HandlerFunc) http.HandlerFunc) {
	if storage == nil {
		panic("storage is nil")
	}

	if auth == nil {
		auth = func(f http.HandlerFunc) http.HandlerFunc { return f }
	}

	collectionHandlers := map[string]apiHandlerFunc{
		"GET":     getAll,
		"POST":    create,
		"DELETE":  deleteAll,
		"OPTIONS": optionsCollection,
	}

	resourceHandlers := map[string]apiHandlerFunc{
		"GET":     get,
		"PUT":     update,
		"DELETE":  del,
		"OPTIONS": optionsResource,
	}

	router.HandleFunc("/{collection}", auth(chooseAndInitialize(collectionHandlers, storage)))
	router.HandleFunc("/{collection}/{id}", auth(chooseAndInitialize(resourceHandlers, storage)))
}
Example #5
0
func Register(rtr *mux.Router, bus *eventbus.EventBus) {
	rtr.HandleFunc("/ws", upgradeHandler).Methods("GET")
	bus.RegisterHandler(serviceStateChanged)
	bus.RegisterHandler(viewStateChanged)

	go h.run()
}
func registerIdentityRoot(s *CollectorSuite, r *mux.Router) {
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, `
				{
					"versions": {
						"values": [
							{
								"status": "experimental",
								"id": "v3.0",
								"links": [
									{ "href": "%s", "rel": "self" }
								]
							},
							{
								"status": "stable",
								"id": "v2.0",
								"links": [
									{ "href": "%s", "rel": "self" }
								]
							}
						]
					}
				}
				`, s.server.URL+"/v3/", s.server.URL+"/v2.0/")
	})
}
Example #7
0
func setupWebsiteRoutes(r *mux.Router) {
	// serve static files
	r.HandleFunc("/static/config.js", webConfigHandler)
	r.PathPrefix("/static").Handler(http.FileServer(http.Dir("web/build/")))

	r.HandleFunc("/version", versionHandler).Methods("GET")

	// docs
	for _, p := range webDocPages {
		r.HandleFunc(p.route, webDocHandler)
	}

	// lists
	r.HandleFunc("/list/{kind}/by-{order}", webListHandler)

	// user
	r.HandleFunc("/{user}", webUserHandler)
	u := r.PathPrefix("/{user}").Subrouter()
	u.StrictSlash(true)

	u.HandleFunc("/", webUserHandler).Methods("GET")
	// u.HandleFunc("/user/add", webUserAddHandler).Methods("POST")
	// u.HandleFunc("/user/info", webUserInfoHandler).Methods("GET", "POST")
	// u.HandleFunc("/user/pass", webUserPassHandler).Methods("POST")

	// user/dataset
	u.HandleFunc("/{dataset}", webDsHomeHandler)
	// d := u.PathPrefix("/{dataset}@{ref}").Subrouter()
	// d.StrictSlash(true)

	// d.HandleFunc("/", webDsHomeHandler)
	// d.HandleFunc("/blob/", webDsBlobHandler)
}
func registerIdentityTenants(s *CollectorSuite, r *mux.Router) {
	r.HandleFunc("/v2.0/tenants", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("X-Auth-Token", s.Token)

		w.Header().Add("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)

		fmt.Fprintf(w, `
			{
				"tenants": [
					{
						"description": "Test tenat",
						"enabled": true,
						"id": "%s",
						"name": "%s"
					},
					{
						"description": "admin tenant",
						"enabled": true,
						"id": "%s",
						"name": "%s"
					}
				],
				"tenants_links": []
			}
		`, s.Tenant1ID, s.Tenant1Name, s.Tenant2ID, s.Tenant2Name)
	}).Methods("GET")
}
Example #9
0
// registerWebuiHandler registers handlers for serving web UI
func registerWebuiHandler(router *mux.Router) {
	// Setup the router to serve the web UI
	goPath := os.Getenv("GOPATH")
	if goPath != "" {
		webPath := goPath + "/src/github.com/contiv/contivmodel/www/"

		// Make sure we have the web UI files
		_, err := os.Stat(webPath)
		if err != nil {
			webPath = goPath + "/src/github.com/contiv/netplugin/" +
				"Godeps/_workspace/src/github.com/contiv/contivmodel/www/"
			_, err := os.Stat(webPath)
			if err != nil {
				log.Errorf("Can not find the web UI directory")
			}
		}

		log.Infof("Using webPath: %s", webPath)

		// serve static files
		router.PathPrefix("/web/").Handler(http.StripPrefix("/web/", http.FileServer(http.Dir(webPath))))

		// Special case to serve main index.html
		router.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
			http.ServeFile(rw, req, webPath+"index.html")
		})
	}

	// proxy Handler
	router.PathPrefix("/proxy/").HandlerFunc(proxyHandler)
}
Example #10
0
func Register(rtr *mux.Router, client_ service.ServiceIf) {
	client = client_
	rtr.HandleFunc("/", RedirectHandler).Methods("GET")
	rtr.HandleFunc("/status", StatusHandler).Methods("GET")
	rtr.PathPrefix("/").Handler(http.FileServer(
		&assetfs.AssetFS{Asset, AssetDir, "/"}))
}
Example #11
0
func handlePlayground(r *mux.Router) {
	r = r.PathPrefix("/api/playground").Subrouter()

	r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		results.View("playground/form", nil, w)
	})
}
Example #12
0
// addApiHandlers adds each API handler to the given router.
func addApiHandlers(router *mux.Router, db *sqlx.DB) {
	for route, funcs := range api.ApiHandlers() {
		for method, f := range funcs {
			router.HandleFunc(apiPath+route, auth.Use(wrapApiHandler(f, funcs.Methods(), db), auth.RequireLogin)).Methods(method.String())
		}
	}
}
Example #13
0
func AddStatusHandler(router *mux.Router) {
	router.HandleFunc("/status.txt", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Fprint(rw, "alive")
		return
	})
	return
}
Example #14
0
func (md *MandrillWebhook) Register(router *mux.Router, acc telegraf.Accumulator) {
	router.HandleFunc(md.Path, md.returnOK).Methods("HEAD")
	router.HandleFunc(md.Path, md.eventHandler).Methods("POST")

	log.Printf("Started the webhooks_mandrill on %s\n", md.Path)
	md.acc = acc
}
func getNegroniHandlers(ctx *RouterContext.RouterContext, router *mux.Router) []negroni.Handler {
	tmpArray := []negroni.Handler{}

	// fullRecoveryStackMessage := GlobalConfigSettings.Common.DevMode

	routerRecoveryWrapper := &tmpRouterRecoveryWrapper{ctx.Logger}

	// tmpArray = append(tmpArray, gzip.Gzip(gzip.DefaultCompression))
	tmpArray = append(tmpArray, NewRecovery(routerRecoveryWrapper.onRouterRecoveryError)) //recovery.JSONRecovery(fullRecoveryStackMessage))
	tmpArray = append(tmpArray, negroni.NewLogger())

	if ctx.Settings.IsDevMode() {
		middleware := stats.New()
		router.HandleFunc("/stats.json", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")

			stats := middleware.Data()

			b, _ := json.Marshal(stats)

			w.Write(b)
		})
		tmpArray = append(tmpArray, middleware)
	}

	return tmpArray
}
Example #16
0
func SetupRoutes(r *mux.Router) {
	adminRouter := r.PathPrefix("/admin").Subrouter()
	adminRouter.Handle("/users", authAdminUser(admin.UserIndexController)).Methods("GET")
	adminRouter.Handle("/users/{id:[0-9]+}/edit", authAdminUser(admin.UserEditController)).Methods("GET")
	adminRouter.Handle("/users/{id:[0-9]+}/edit", authAdminUser(admin.UserUpdateController)).Methods("POST")
	adminRouter.Handle("/users/{id:[0-9]+}/delete", authAdminUser(admin.UserDeleteController)).Methods("POST")

	apiRouter := r.PathPrefix("/api").Subrouter()
	apiRouter.Handle("/jobs", authUser(job.IndexController)).Methods("GET")
	apiRouter.Handle("/jobs/{id:[0-9]+}", authUser(job.ShowController)).Methods("GET")
	apiRouter.Handle("/jobs", authUser(job.CreateController)).Methods("POST")
	apiRouter.Handle("/jobs/{id:[0-9]+}", authUser(job.UpdateController)).Methods("PUT")
	apiRouter.Handle("/jobs/{id:[0-9]+}", authUser(job.DeleteController)).Methods("DELETE")
	apiRouter.Handle("/plans/{id:[0-9]+}", authUser(plan.ShowController)).Methods("GET")
	apiRouter.Handle("/plans", authUser(plan.CreateController)).Methods("POST")
	apiRouter.Handle("/plans/{id:[0-9]+}", authUser(plan.UpdateController)).Methods("PUT")
	apiRouter.Handle("/plans/{id:[0-9]+}", authUser(plan.DeleteController)).Methods("DELETE")

	r.Handle("/app", authUser(app.AppController)).Methods("GET")

	r.Handle("/user", redirectUser(user.CreateController)).Methods("POST")
	r.Handle("/user/edit", authUser(user.EditController)).Methods("GET")
	r.Handle("/user/edit", authUser(user.UpdateController)).Methods("POST")
	r.Handle("/user/sign_in", redirectUser(user.LoginController)).Methods("POST")
	// Ideally we want this to be a DELETE method but it is a bitch to send a DELETE
	// request client side.  POST will do for now.
	r.Handle("/user/sign_out", authUser(user.LogoutController)).Methods("POST")

	r.HandleFunc("/mobile", mobile.MobileController).Methods("GET")
	r.Handle("/", redirectUser(marketing.HomeController)).Methods("GET")
}
Example #17
0
func InitAppHandlers(r *mux.Router, oAuth *OAuthHandler) {
	r.HandleFunc("/", handleIndex).Methods("GET")
	r.HandleFunc("/sales/pending/{partnerId}", oAuth.MiddlewareFunc(handlePendingSalesOrders)).Methods("GET")
	r.HandleFunc("/sales/approve/{salesOrderId}", oAuth.MiddlewareFunc(handleApproveSalesOrder)).Methods("POST")
	r.HandleFunc("/sales/reject/{salesOrderId}", oAuth.MiddlewareFunc(handleRejectSalesOrder)).Methods("POST")
	r.HandleFunc("/products", handleProducts).Methods("GET")
}
Example #18
0
File: muxer.go Project: liyu4/home
// MakeMuxer creates a http.Handler to manage all list operations. If
// a prefix is given, that prefix will be the first part of the
// url. This muxer will provide the following handlers and return a
// RESTful 404 on all others.
//
//  GET     prefix + /        Get all lists.
//  POST    prefix + /        Create a new list.
//
//  GET     prefix + /{key}/  Get the list for the given key.
//  PUT     prefix + /{key}/  Update the list with the given key.
//  DELETE  prefix + /{key}/  Delete the list with the given key.
//
// See the functions related to these urls for more details on what
// each one does and the requirements behind it.
func MakeMuxer(prefix string) http.Handler {
	var m *mux.Router

	// Pass through the prefix if we got one.
	if prefix == "" {
		m = mux.NewRouter()
	} else {
		m = mux.NewRouter().PathPrefix(prefix).Subrouter()
	}

	// Get all lists.
	m.HandleFunc("/", GetAllLists).Methods("GET")

	// Make a new list.
	m.HandleFunc("/", PostList).Methods("POST")

	// Singe list operations.
	m.HandleFunc("/{key}/", GetList).Methods("GET")
	m.HandleFunc("/{key}/", PutList).Methods("PUT")
	m.HandleFunc("/{key}/", DeleteList).Methods("DELETE")

	// Everything else fails.
	m.HandleFunc("/{path:.*}", gorca.NotFoundFunc)

	return m
}
Example #19
0
func CompaniesInterfaceRoutes(r *mux.Router, i CompaniesInterface) {
	r.HandleFunc("/companies", i.Post).Methods("POST")
	r.HandleFunc("/companies/{globalId}", i.globalIdPut).Methods("PUT")
	r.HandleFunc("/companies/{globalId}/validate", i.globalIdvalidateGet).Methods("GET")
	r.HandleFunc("/companies/{globalId}/contracts", i.globalIdcontractsGet).Methods("GET")
	r.HandleFunc("/companies/{globalId}/info", i.globalIdinfoGet).Methods("GET")
}
Example #20
0
func ConfigFormHandler(router *mux.Router) {
	router.HandleFunc("/submit", public.AuthUserVerifierWrapper(handleFormSubmit))
	router.HandleFunc("/upload", public.AuthUserVerifierWrapper(handleFormFileUpload))
	router.HandleFunc("/view", public.AuthUserVerifierWrapper(handleFormView))

	router.HandleFunc("/recomm/{hash}", handleRecommendation)
	router.HandleFunc("/recomm/{hash}/upload", public.RequestMethodGuard(handleRecommendationUpload, "post", "put"))
}
Example #21
0
func addBatchEndpoint(spec *APISpec, Muxer *mux.Router) {
	log.WithFields(logrus.Fields{
		"prefix": "main",
	}).Debug("Batch requests enabled for API")
	apiBatchPath := spec.Proxy.ListenPath + "tyk/batch/"
	thisBatchHandler := BatchRequestHandler{API: spec}
	Muxer.HandleFunc(apiBatchPath, thisBatchHandler.HandleBatchRequest)
}
Example #22
0
func RegisterRoutes(apiRouter *mux.Router) {
	apiRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNotFound)
	})

	apiRouter.HandleFunc("/v1/characters", controllers.CharacterListControllerInstance.Get).Methods("GET")
	apiRouter.HandleFunc("/v1/characters/{characterName}", controllers.CharacterControllerInstance.Get).Methods("GET")
}
Example #23
0
func SetupHTTPRoutes(router *mux.Router) {
	router.HandleFunc("/", controllers.MainHandler)
	router.HandleFunc("/openidcallback", controllers.LoginCallbackHandler)
	router.HandleFunc("/startLogin", controllers.LoginHandler)
	router.HandleFunc("/logout", controllers.LogoutHandler)
	router.HandleFunc("/{param}", controllers.ExampleHandler)

}
Example #24
0
func InitServer(r *mux.Router) {

	s := &Server{securecookie.New([]byte("MiaMySuperSecret"), []byte("MiaMySuperSecret"))}

	r.HandleFunc("/send", s.secure(s.handleSend))
	r.HandleFunc("/login", s.handleLogin)

}
Example #25
0
func SetRoute(router *mux.Router, path, name, method string, handlerFunc func(w http.ResponseWriter, r *http.Request)) *mux.Router {
	var handler http.HandlerFunc

	handler = handlerFunc
	handler = logger.Logger(handler, name)
	router.HandleFunc(path, handler).Methods(method)

	return router
}
Example #26
0
func serveStatic(router *mux.Router) {
	handler := func(w http.ResponseWriter, request *http.Request) {
		vars := mux.Vars(request)
		filepath := "/" + vars["path"]
		w.Header().Set("Cache-Control", "public, max-age=43200")
		http.ServeFile(w, request, path.Join("client/", filepath))
	}
	router.HandleFunc("/{path:.*}", handler)
}
Example #27
0
func SetupRoutes(r *mux.Router) {
	auth.InvalidTokenHandler = forbiddenHandler
	auth.TokenValidated = tokenValidated
	auth.SecretKey = "secret"

	r.HandleFunc("/login", loginHandler).Methods("POST")
	r.HandleFunc("/user", auth.HandlerFunc(userHandler))
	r.HandleFunc("/public", publicHandler)
}
// Sets up all of the mux router routes for the methods on a given resource.
// Sets up for both item or list route types, depending on the routeType param
func (rm *ResourceManager) setMethodRoutes(res Resource, routeType string) {
	resType := reflect.TypeOf(res)
	for i := 0; i < resType.NumMethod(); i++ {
		method := resType.Method(i)
		mName := method.Name

		var mType string
		for idx := range rm.AllowedMethods {
			httpMethod := rm.AllowedMethods[idx]
			// See if this method starts with an HTTP Method
			if strings.HasPrefix(mName, strings.Title(strings.ToLower(httpMethod))) {
				mType = httpMethod
				break
			}
		}

		prefix := strings.Title(strings.ToLower(mType)) + routeType
		if mType == "" || !strings.HasPrefix(mName, prefix) {
			// If this is not of the form of (Method Type)List(Optional Suffix) do not add.
			// Example should look like PostListFoobar or PostList
			continue
		}

		name := fmt.Sprintf("%s.%s", res.ResourceFullName(), mName)
		// Create the handler closure around the method call
		handler := func(w http.ResponseWriter, r *http.Request) {
			method.Func.Call([]reflect.Value{
				reflect.ValueOf(res), reflect.ValueOf(w), reflect.ValueOf(r)})
		}

		// We'll Add it into the routes for the methods.
		// For a blog list foo method, the route looks like this /blog/foo/
		// and for a blog route item,
		// it looks like this /blog/{blog}/foo where {blog} is the blog id

		var routePath string
		if prefix == mName {
			// If this is one of the base paths, just set it at root
			routePath = "/"
		} else {
			// If this is a method path, set it at /(root)/(method name)
			shortName := CamelToUnderscore(strings.TrimPrefix(mName, prefix))
			routePath = fmt.Sprintf("/%s/", shortName)
		}

		var router *mux.Router
		if routeType == "Item" {
			router = rm.GetRoute(res, "item").Subrouter()
			handler = rm.itemHandler(res, reflect.ValueOf(handler))
		} else {
			router = rm.GetRoute(res, "list").Subrouter()
			handler = rm.listHandler(res, reflect.ValueOf(handler))
		}
		route := router.HandleFunc(routePath, handler).Methods(mType).Name(name)
		rm.RegisterRoute(res, mName, route)
	}
}
Example #29
0
func (tabula *TabulaRasa) WebPluginSetup(router *mux.Router) {

	router.HandleFunc("/plugins/tabularasa", func(w http.ResponseWriter, r *http.Request) {

		tabula.TabulaRasta()

	})

}
Example #30
0
func (raftPeer *RaftPeer) ListenAndServe(router *mux.Router, httpServer raft.HTTPMuxer) error {
	var err error
	rand.Seed(time.Now().UnixNano())

	// Setup commands.
	raft.RegisterCommand(&TransactionBatchCommand{})
	raft.RegisterCommand(&SetCommand{})

	if err := os.MkdirAll(raftPeer.path, 0744); err != nil {
		log.Fatalf("Unable to create path: %v", err)
	}

	log.Printf("Initializing Raft Server: %s", raftPeer.path)

	// Initialize and start Raft server.
	transporter := raft.NewHTTPTransporter("/raft")
	//NewServer(name string, path string, transporter Transporter, stateMachine StateMachine, context interface{}, connectionString string) (*Server, error) {
	raftPeer.raftServer, err = raft.NewServer(raftPeer.name, raftPeer.path, transporter, nil, raftPeer.db, "")
	if err != nil {
		log.Fatal(err)
	}
	transporter.Install(raftPeer.raftServer, httpServer)
	raftPeer.raftServer.Start()

	// Join to leader if specified.
	if raftPeer.leaderAddress != "" {
		log.Println("Attempting to join leader:", raftPeer.leaderAddress)

		if !raftPeer.raftServer.IsLogEmpty() {
			log.Fatal("Cannot join with an existing log")
		}
		if err := raftPeer.Join(raftPeer.leaderAddress); err != nil {
			log.Fatal(err)
		}

		// Initialize the server by joining itself.
	} else if raftPeer.raftServer.IsLogEmpty() {
		log.Println("Initializing new cluster")

		_, err := raftPeer.raftServer.Do(&raft.DefaultJoinCommand{
			Name:             raftPeer.raftServer.Name(),
			ConnectionString: raftPeer.connectionString(),
		})
		if err != nil {
			log.Fatal(err)
		}

	} else {
		log.Println("Recovered from log")
	}

	router.HandleFunc("/join", raftPeer.joinHandler).Methods("POST")

	fmt.Printf("Raft listening\n")
	return nil // TODO return errors.
}