示例#1
0
func (s *GossamerServer) Start() {
	goji.Get("/", s.HandleWebUiIndex)
	goji.Get("/things.html", s.HandleWebUiThings)
	goji.Get("/sensors.html", s.HandleWebUiSensors)
	goji.Get("/observations.html", s.HandleWebUiObservations)
	goji.Get("/observedproperties.html", s.HandleWebUiObservedProperties)
	goji.Get("/locations.html", s.HandleWebUiLocations)
	goji.Get("/datastreams.html", s.HandleWebUiDatastreams)
	goji.Get("/featuresofinterest.html", s.HandleWebUiFeaturesOfInterest)
	goji.Get("/historiclocations.html", s.HandleWebUiHistoricLocations)
	goji.Get("/css/*", s.HandleWebUiResources)
	goji.Get("/img/*", s.HandleWebUiResources)
	goji.Get("/js/*", s.HandleWebUiResources)

	goji.Get("/v1.0", s.handleRootResource)
	goji.Get("/v1.0/", s.handleRootResource)

	goji.Get("/v1.0/*", s.HandleGet)
	goji.Post("/v1.0/*", s.HandlePost)
	goji.Put("/v1.0/*", s.HandlePut)
	goji.Delete("/v1.0/*", s.HandleDelete)
	goji.Patch("/v1.0/*", s.HandlePatch)

	flag.Set("bind", ":"+strconv.Itoa(s.port))

	log.Println("Start Server on port ", s.port)
	goji.Serve()
}
示例#2
0
func SetupRoutes() {
	for _, route := range routes {
		for _, method := range route.methods {
			switch method {
			case "GET":
				goji.Get(route.url, route.handler)
				break
			case "POST":
				goji.Post(route.url, route.handler)
				break
			case "PUT":
				goji.Put(route.url, route.handler)
				break
			case "PATCH":
				goji.Patch(route.url, route.handler)
				break
			case "DELETE":
				goji.Delete(route.url, route.handler)
				break
			default:
				goji.Handle(route.url, route.handler)
			}
		}
	}
}
示例#3
0
文件: bamboo.go 项目: rthomas/bamboo
func initServer(conf *configuration.Configuration, conn *zk.Conn, eventBus *event_bus.EventBus) {
	stateAPI := api.StateAPI{Config: conf, Zookeeper: conn}
	serviceAPI := api.ServiceAPI{Config: conf, Zookeeper: conn}
	eventSubAPI := api.EventSubscriptionAPI{Conf: conf, EventBus: eventBus}

	conf.StatsD.Increment(1.0, "restart", 1)
	// Status live information
	goji.Get("/status", api.HandleStatus)

	// State API
	goji.Get("/api/state", stateAPI.Get)

	// Service API
	goji.Get("/api/services", serviceAPI.All)
	goji.Post("/api/services", serviceAPI.Create)
	goji.Put("/api/services/:id", serviceAPI.Put)
	goji.Delete("/api/services/:id", serviceAPI.Delete)

	goji.Post("/api/marathon/event_callback", eventSubAPI.Callback)

	// Static pages
	goji.Get("/*", http.FileServer(http.Dir("./webapp")))

	registerMarathonEvent(conf)

	goji.Serve()
}
示例#4
0
文件: main.go 项目: t2y/misc
func main() {
	Logger.Formatter = new(logrus.JSONFormatter)

	// init
	db := InitDatabase("./myapp.db")
	defer db.Close()

	// middleware
	goji.Use(func(c *web.C, h http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			c.Env["DB"] = db
			h.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)

	})
	goji.Use(glogrus.NewGlogrus(Logger, "myapp"))
	goji.Use(middleware.Recoverer)
	goji.Use(middleware.NoCache)
	goji.Use(SetProperties)

	// handlers
	goji.Get("/users/", ListUsers)
	goji.Get(regexp.MustCompile(`/users/(?P<name>\w+)$`), GetUser)
	goji.Get("/*", AllMatchHandler)
	goji.Post(regexp.MustCompile(`/users/(?P<name>\w+)$`), RegisterUser)
	goji.Put("/users/:name", UpdateUserInfo)
	goji.Delete("/users/:name", DeleteUserInfo)

	goji.Serve()
}
示例#5
0
文件: server.go 项目: jf/gwp
func main() {
	goji.Get("/post/:id", post.HandleGet)
	goji.Post("/post", post.HandlePost)
	goji.Put("/post/:id", post.HandlePut)
	goji.Delete("/post/:id", post.HandleDelete)
	goji.Serve()

}
示例#6
0
func InitRoutes() {
	goji.Get("/users", UserList)
	goji.Get("/users/:id", UserView)
	goji.Delete("/users/:id", UserDelete)
	goji.Post("/users", UserCreate)
	goji.Put("/users/:id", UserUpdate)
	goji.Get("/", Index)
}
示例#7
0
文件: main.go 项目: velugu7777/vtodos
func main() {
	goji.Get("/todo", todos)
	goji.Post("/todo/newTodo", newTodo)
	goji.Get("/todo:id", getTodo)
	goji.Put("/todo:id", putTodo)
	goji.Delete("/todo:id", delTodo)
	goji.Serve()
}
示例#8
0
func main() {
	goji.Get("/recipes/:id", getRecipes)
	goji.Get("/recipes", getAllRecipes)
	goji.Delete("/recipes/:id", deleteRecipe)
	goji.Put("/recipes", putRecipe)

	goji.Serve()
}
示例#9
0
func defineHandlers() {
	pref := "/rest/:service/:region"
	goji.Get(pref+"/:resource", indexHandler)
	goji.Get(pref+"/:resource/:id", showHandler)
	goji.Put(pref+"/:resource/:id", updateHandler)
	goji.Post(pref+"/:resource", createHandler)
	goji.Delete(pref+"/:resource/:id", deleteHandler)
	goji.Post(pref+"/action/:action", serviceActionHandler)
	goji.Post(pref+"/:resource/action/:action", collectionActionHandler)
	goji.Post(pref+"/:resource/:id/action/:action", resourceActionHandler)
}
示例#10
0
文件: main.go 项目: velugu7777/vtodo
func main() {
	goji.Get("/", index)
	goji.Get("/assets/*", http.FileServer(http.Dir("./dist")))
	goji.Get("/api/todos", todos)
	goji.Post("/api/todos", newTodo)
	goji.Put("/api/todos/:id", putTodo)
	goji.Delete("/api/todos/:id", delTodo)

	goji.NotFound(index)

	goji.Serve()
}
示例#11
0
func main() {
	err := godotenv.Load()
	if err != nil {
		panic("Error loading .env file")
	}

	sess, err := mgo.Dial(os.Getenv("AA_STATS_DB_ADDRESS"))
	if err != nil {
		panic(err)
	}
	defer sess.Close()
	sess.SetMode(mgo.Monotonic, true)

	DB = sess.DB(os.Getenv("AA_STATS_DB_NAME"))

	// Add routes to the global handler
	goji.Get("/users/:id", returnUser)
	goji.Get("/users", returnUsers)
	goji.Post("/users", newUser)

	goji.Get("/games/:id", returnGame)
	goji.Get("/games", returnGames)
	goji.Post("/games", newGame)

	goji.Get("/sessions/:id", returnGameSession)
	goji.Put("/sessions/:id", updateSession)
	goji.Get("/sessions", returnGameSessions)
	goji.Post("/sessions", newGameSession)

	goji.Post("/rounds", newRound)

	goji.Get("/", root)

	goji.Use(HalResponseMiddleware)
	goji.Use(EnsureJsonContentTypeMiddleware)
	goji.Use(CORSMiddleware)

	goji.Serve()
}
示例#12
0
func main() {
	//
	// Event queue hadling
	//
	err := players.StartEventProcessor()
	if err != nil {
		fmt.Printf("%+v", err.Error)
		println("Could not initialize event queue. Exiting")
		os.Exit(1)
	}

	//
	// HTTP Serving
	//
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"*"},
		AllowedMethods: []string{"GET", "PUT", "PATCH", "POST", "OPTIONS", "DELETE"},
	})
	goji.Use(c.Handler)
	goji.Use(middleware.TokenHandler)

	goji.Post("/login", appHandler(login))

	goji.Get("/players", appHandler(listAllPlayers))
	goji.Post("/players", appHandler(createNewPlayer))
	goji.Get("/players/quotes", appHandler(getAllPlayerQuotes))
	goji.Get("/players/:uuid", appHandler(getPlayer))
	goji.Put("/players/:uuid", appHandler(updatePlayer))
	goji.Post("/players/:uuid/quotes", appHandler(addPlayerQuote))
	goji.Get("/players/:uuid/profile", appHandler(getPlayerProfile))
	goji.Put("/players/:uuid/profile", appHandler(updatePlayerProfile))
	goji.Get("/players/:uuid/user", appHandler(getUserForPlayer))
	goji.Put("/players/:uuid/user", appHandler(setUserForPlayer))
	goji.Put("/players/:uuid/user/password", appHandler(setUserPassword))
	goji.Put("/players/:uuid/user/settings", appHandler(setUserSettings))
	goji.Put("/players/:uuid/user/admin", appHandler(setUserAdmin))
	goji.Put("/players/:uuid/gossip", appHandler(setPlayerGossip))
	goji.Patch("/players/:uuid/gossip", appHandler(setPlayerGossip))
	goji.Delete("/players/:uuid/gossip", appHandler(resetPlayerGossip))
	goji.Get("/players/:uuid/debts", appHandler(showPlayerDebt))
	goji.Delete("/players/:uuid/debts", appHandler(resetPlayerDebts))
	goji.Get("/players/:uuid/credits", appHandler(showPlayerCredits))
	goji.Post("/players/:uuid/debts", appHandler(addPlayerDebt))
	goji.Delete("/players/:uuid/debts/:debtuuid", appHandler(settlePlayerDebt))
	goji.Put("/players/:uuid/votes", appHandler(setPlayerVotes))
	goji.Patch("/players/:uuid/votes", appHandler(setPlayerVotes))
	goji.Post("/players/notification_test", appHandler(testPlayerNotify))

	goji.Post("/users", appHandler(createNewUser))

	goji.Get("/locations", appHandler(listAllLocations))
	goji.Post("/locations", appHandler(createNewLocation))
	goji.Get("/locations/:uuid", appHandler(getLocation))
	goji.Put("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Patch("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Post("/locations/:uuid/pictures", appHandler(addLocationPicture))

	goji.Get("/tournaments", appHandler(listAllTournaments))
	goji.Post("/tournaments", appHandler(createNewTournament))
	goji.Get("/tournaments/:uuid", appHandler(getTournament))
	goji.Put("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Patch("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Put("/tournaments/:uuid/played", appHandler(setTournamentPlayed))
	goji.Get("/tournaments/:uuid/result", appHandler(getTournamentResult))
	goji.Put("/tournaments/:uuid/result", appHandler(setTournamentResult))
	goji.Post("/tournaments/:uuid/noshows", appHandler(addTournamentNoShow))
	goji.Delete("/tournaments/:uuid/noshows/:playeruuid", appHandler(removeTournamentNoShow))

	goji.Get("/seasons", appHandler(listAllSeasons))
	goji.Get("/seasons/stats", appHandler(getTotalStats))
	goji.Get("/seasons/standings", appHandler(getTotalStandings))
	goji.Get("/seasons/titles", appHandler(getTotalTitles))
	goji.Get("/seasons/:year/tournaments", appHandler(listTournamentsBySeason))
	goji.Get("/seasons/:year/standings", appHandler(getSeasonStandings))
	goji.Get("/seasons/:year/titles", appHandler(getSeasonTitles))
	goji.Get("/seasons/:year/stats", appHandler(getSeasonStats))

	goji.Get("/caterings", appHandler(listAllCaterings))
	goji.Post("/caterings", appHandler(createNewCatering))
	goji.Get("/caterings/:uuid", appHandler(getCatering))
	goji.Put("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Patch("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Post("/caterings/:uuid/votes", appHandler(addCateringVote))
	goji.Put("/caterings/:uuid/votes/:playeruuid", appHandler(updateCateringVote))

	goji.Get("/news", appHandler(listAllNews))
	goji.Get("/news/:uuid", appHandler(getNewsItem))
	goji.Patch("/news/:uuid", appHandler(updateNewsItem))
	goji.Post("/news", appHandler(createNewNewsItem))
	goji.Post("/news/:uuid/comments", appHandler(addNewsComment))
	// TODO: Comment updates/deletion

	goji.Serve()
}
示例#13
0
func main() {
	mc, err := actions.GetConstellation(config.Name, config.SentinelConfigFile, config.GroupName, config.SentinelHostAddress)
	if err != nil {
		log.Fatal("Unable to connect to constellation")
	}
	//log.Print("Starting refresh ticker")

	// Try to set to the IP the sentinel is bound do
	//flag.Set("bind", mc.SentinelConfig.Host+":8000")

	//go RefreshData()
	_, _ = mc.GetPodMap()
	//for _, pod := range pm {
	//handlers.NodeMaster.AddNode(pod.Master)
	//for _, node := range pod.Nodes { handlers.NodeMaster.AddNode(&node) }
	//}
	mc.IsBalanced()
	handlers.ManagedConstellation = mc
	_ = handlers.NewPageContext()
	if handlers.ManagedConstellation.AuthCache == nil {
		log.Print("Uninitialized AuthCache, StartCache not called, calling now")
		handlers.ManagedConstellation.StartCache()
	}
	log.Printf("Main Cache Stats: %+v", handlers.ManagedConstellation.AuthCache.GetStats())
	log.Printf("Hot Cache Stats: %+v", handlers.ManagedConstellation.AuthCache.GetHotStats())
	//log.Printf("MC:%+v", handlers.ManagedConstellation)

	// HTML Interface URLS
	goji.Get("/constellation/", handlers.ConstellationInfoHTML) // Needs moved? instance tree?
	goji.Get("/dashboard/", handlers.Dashboard)                 // Needs moved? instance tree?
	goji.Get("/constellation/addpodform/", handlers.AddPodForm)
	goji.Post("/constellation/addpod/", handlers.AddPodHTML)
	goji.Post("/constellation/addsentinel/", handlers.AddSentinelHTML)
	goji.Get("/constellation/addsentinelform/", handlers.AddSentinelForm)
	goji.Get("/constellation/rebalance/", handlers.RebalanceHTML)
	//goji.Get("/pod/:podName/dropslave", handlers.DropSlaveHTML)
	goji.Get("/pod/:podName/addslave", handlers.AddSlaveHTML)
	goji.Post("/pod/:podName/addslave", handlers.AddSlaveHTMLProcessor)
	goji.Post("/pod/:name/failover", handlers.DoFailoverHTML)
	goji.Post("/pod/:name/reset", handlers.ResetPodProcessor)
	goji.Post("/pod/:name/balance", handlers.BalancePodProcessor)
	goji.Get("/pod/:podName", handlers.ShowPod)
	goji.Get("/pods/", handlers.ShowPods)
	goji.Get("/nodes/", handlers.ShowNodes)
	goji.Get("/node/:name", handlers.ShowNode)
	goji.Get("/", handlers.Root) // Needs moved? instance tree?

	// API URLS
	goji.Get("/api/knownpods", handlers.APIGetPods)
	goji.Put("/api/monitor/:podName", handlers.APIMonitorPod)
	goji.Post("/api/constellation/:podName/failover", handlers.APIFailover)

	goji.Get("/api/pod/:podName", handlers.APIGetPod)
	goji.Put("/api/pod/:podName", handlers.APIMonitorPod)
	goji.Put("/api/pod/:podName/addslave", handlers.APIAddSlave)
	goji.Delete("/api/pod/:podName", handlers.APIRemovePod)
	goji.Get("/api/pod/:podName/master", handlers.APIGetMaster)
	goji.Get("/api/pod/:podName/slaves", handlers.APIGetSlaves)

	goji.Post("/api/node/clone", handlers.Clone) // Needs moved to the node tree
	goji.Get("/api/node/:name", handlers.GetNodeJSON)

	goji.Get("/static/*", handlers.Static) // Needs moved? instance tree?
	//goji.Abandon(middleware.Logger)

	goji.Serve()

}
示例#14
0
文件: main.go 项目: edvakf/httpfs
func serveGoji() {
	goji.Get("/fs/[a-zA-Z0-9._/-]+", httpfs.HandleGet)
	goji.Put("/fs/[a-zA-Z0-9._/-]+", httpfs.HandlePut)
	goji.Delete("/fs/[a-zA-Z0-9._/-]+", httpfs.HandleDelete)
	goji.ServeListener(bind.Socket(":10002"))
}
示例#15
0
func serve(c *cli.Context) {
	client := c.String("consuladdress")
	name := c.String("name")

	// Initialize a new store with consul
	kv, err := libkv.NewStore(
		store.CONSUL, // or "consul"
		[]string{client},
		&store.Config{
			ConnectionTimeout: 10 * time.Second,
		},
	)
	if err != nil {
		log.Fatal("Cannot create store consul")
	}

	prefix := "app/port-authority/config"
	key_apiport := fmt.Sprintf("%s/api_port", prefix)
	//key_uiport := fmt.Sprintf("%s/ui_port", prefix)
	key_rpcport := fmt.Sprintf("%s/rpc_port", prefix)
	key_templatedir := fmt.Sprintf("%s/template_directory", prefix)
	key_airbrakeapikey := fmt.Sprintf("%s/airbrake/api_key", prefix)
	key_airbrakeendpoint := fmt.Sprintf("%s/airbrake/endpoint", prefix)
	havestore := true
	tmp, err := kv.Get(key_apiport)
	if err != nil {
		havestore = false
		log.Printf("Error: %v", err)
	} else {
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s/api_port", prefix)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			port, err := strconv.Atoi(string(tmp.Value))
			if err != nil {
				config.Port = int(port)
			}
		}
	}
	var port_start = 30000
	var port_end = 40000
	if havestore {
		//config.RPCPort, err = kv.Get(key_rpcport)
		log.Printf("Connected to config store")
		tmp, err = kv.Get(key_templatedir)
		if err != nil {
			log.Print("template_directory key not foumd, using /tmp as default!")
			config.TemplateDirectory = "/tmp"
		} else {
			config.TemplateDirectory = string(tmp.Value)
		}

		tmp, err = kv.Get(key_rpcport)
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s/rpc_port", prefix)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			fmt.Printf("rpcport: %s", string(tmp.Value))
			port, err := strconv.Atoi(string(tmp.Value))
			log.Printf("%s %v", port, err)
			if err != nil {
				config.RPCPort = int(port)
			}
		}
		var my_key string
		if name != "" {
			my_key = fmt.Sprintf("%s/%s", prefix, name)
		} else {
			my_key = prefix
		}

		key_portstart := fmt.Sprintf("%s/ports_begin", my_key)
		tmp, err = kv.Get(key_portstart)
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s", key_portstart)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			port, err := strconv.Atoi(string(tmp.Value))
			if err == nil {
				port_start = int(port)
			}
		}

		key_portend := fmt.Sprintf("%s/ports_end", my_key)
		tmp, err = kv.Get(key_portend)
		if err != nil {
			if strings.Contains(err.Error(), "not found") {
				log.Printf("key not found in config store: %s", key_portend)
			} else {
				log.Print("Error on connection: %v", err)
			}
		} else {
			port, err := strconv.Atoi(string(tmp.Value))
			if err == nil {
				port_end = int(port)
			}
		}
	}
	if actions.InitializeRedisClient("127.0.0.1:6379", "") != nil {
		log.Fatal("Can not connect to Redis!")
	}
	log.Printf("Initializing with ports from %d to %d", port_start, port_end)
	err = actions.InitializePorts(port_start, port_end)
	if err != nil {
		if strings.Contains(err.Error(), "already been init") {
			log.Print(err.Error())
		} else {
			log.Printf("Error on init: %v", err)
		}
	}

	if len(config.BindAddress) != 0 {
		flag.Set("bind", config.BindAddress)
	}
	if config.Port == 0 {
		log.Print("ENV contained no port, using default")
		config.Port = 8080
		flag.Set("bind", fmt.Sprintf("%s:%d", config.BindAddress, config.Port))
	}
	if config.RPCPort == 0 {
		config.RPCPort = config.Port + 1
	}

	if config.TemplateDirectory > "" {
		if !strings.HasSuffix(config.TemplateDirectory, "/") {
			config.TemplateDirectory += "/"
		}
	}
	handlers.TemplateBase = config.TemplateDirectory

	config_json, _ := json.Marshal(config)
	if havestore {
		keypair, err := kv.Get(key_airbrakeapikey)
		abendpoint, err := kv.Get(key_airbrakeendpoint)
		if err == nil {
			key := keypair.Value
			//airbrake.Endpoint = "https://api.airbrake.io/notifier_api/v2/notices"
			airbrake.Endpoint = string(abendpoint.Value)
			airbrake.ApiKey = string(key)
			airbrake.Environment = os.Getenv("RVT_ENVIRONMENT")
			if len(airbrake.Environment) == 0 {
				airbrake.Environment = "Development"
			}
		}
	}
	log.Printf("Config: %s", config_json)
	// HTML Interface URLS
	// API URLS
	goji.Put("/api/service/:id", handlers.APIGetOpenPort)
	goji.Get("/api/service/:id", handlers.APIGetPortFromInstance)
	goji.Delete("/api/service/:id", handlers.APIRemoveService)
	goji.Get("/api/port/:port", handlers.APIGetInstanceFromPort)
	goji.Get("/api/ports/inventory/count", handlers.APIGetPortCapacity)
	goji.Get("/api/ports/inventory/list", handlers.APIGetAvailableInventory)
	goji.Get("/api/ports/assigned/count", handlers.APIGetAssignedCount)
	goji.Get("/api/ports/assigned/list", handlers.APIGetAssignedList)
	goji.Serve()
}
示例#16
0
func main() {
	var (
		dburl  = os.Getenv("MONGODB_URL")
		dbname = os.Getenv("MONGODB_NAME")
	)

	if len(dburl) == 0 {
		dburl = DEFAULT_DB_URL
	}

	if len(dbname) == 0 {
		dbname = DEFAULT_DB_NAME
	}

	mdb := NewMongoDB(dburl, dbname)
	defer mdb.session.Close()

	mdb.session.DB(mdb.name).C("tokens").EnsureIndex(mgo.Index{
		Key: []string{"secret", "user_id"},
	})

	mdb.session.DB(mdb.name).C("boards").EnsureIndex(mgo.Index{
		Key: []string{"members.user_id"},
	})

	mdb.session.DB(mdb.name).C("tokens").EnsureIndex(mgo.Index{
		Key: []string{"board_id"},
	})

	goji.Get("/users",
		GetUsers)
	goji.Get("/users/:user_id",
		GetUser)

	goji.Get("/boards",
		GetBoards)
	goji.Get("/boards/:board_id",
		GetBoard)
	goji.Get("/boards/:board_id/members",
		GetMembers)
	goji.Get("/boards/:board_id/tickets",
		GetTickets)

	goji.Post("/boards",
		AddBoard)
	goji.Post("/boards/:board_id/members",
		AddMember)
	goji.Post("/boards/:board_id/tickets",
		AddTicket)

	goji.Delete("/boards/:board_id",
		RemoveBoard)
	goji.Delete("/boards/:board_id/members/:member_id",
		RemoveMember)
	goji.Delete("/boards/:board_id/tickets/:ticket_id",
		RemoveTicket)

	goji.Put("/boards/:board_id",
		UpdateBoard)
	goji.Put("/boards/:board_id/size",
		UpdateBoardSize)
	goji.Put("/boards/:board_id/members/:member_id",
		UpdateBoardMember)
	goji.Put("/boards/:board_id/tickets/:ticket_id",
		UpdateTicket)
	goji.Put("/boards/:board_id/tickets/:ticket_id/position",
		UpdateTicketPosition)

	goji.Use(mdb.Middleware)
	goji.Use(authenticate)

	goji.Serve()
	return
}
示例#17
0
func main() {
	//init DB user and DB logging
	gest.Db = InitDbUser()
	//close all db at end of program
	//defer gest.Db.Close()

	defer gest.Db.Close()

	//DbCreateUser(gest.Db)
	DbCreateUser(gest.Db)

	// START ROUTING API //

	//this is just a try to show it work :)
	goji.Get("/api", IndexShit)

	goji.Post("/api/session/create", CreateSession)

	goji.Post("/api/user/create", CreateProfile)

	goji.Get("/api/user/profile/me", MyProfile)
	goji.Get("/api/user/profile/:login", GetProfile)
	goji.Put("/api/user/profile/password", EditPassword)
	goji.Put("/api/user/profile/login", EditLogin)
	goji.Put("/api/user/profile/email", EditEmail)
	goji.Put("/api/user/profile/name", EditName)
	goji.Put("/api/user/profile/bio", EditBio)
	goji.Put("/api/user/profile/orientation", EditOrientation)
	goji.Put("/api/user/profile/birth_date", EditBirthDate)

	goji.Get("/api/exist/:login", IsUserExist)

	goji.Get("/api/user/block", ListBlock)

	goji.Post("/api/user/block/:login", BlockUser)
	goji.Delete("/api/user/block/:login", UnblockUser)

	goji.Post("/api/user/report/:login", ReportUser)

	goji.Post("/api/user/tag", AddTag)
	goji.Get("/api/user/tag/:login", ListTag)
	goji.Delete("/api/user/tag/:id", DeleteTag)

	goji.Post("/api/user/image", AddImage)
	goji.Get("/api/user/image", ListImage)
	goji.Delete("/api/user/image/:id", DelImage)

	goji.Get("/api/user/like", Likes)
	goji.Post("/api/user/like/:login", Like)
	goji.Delete("/api/user/like/:login", DelLike)

	goji.Get("/api/user/match", MyMatchs)

	goji.Get("/api/user/history", GetVisiteHistory)

	goji.Get("/api/user/message/:login", GetMessage)
	goji.Post("/api/user/message/:login", SendMessage)

	goji.Get("/api/user/notifications", GetNotification)
	goji.Get("/api/user/nbnotifications", GetNbNotification)

	//END OF ROUTING API//

	//Start of web version//
	goji.Get("/page1", Hihi)
	goji.Get("/page2", Hihi)
	goji.Get("/", Hihi)

	goji.Get("/assets/*", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets"))))
	goji.Get("/Images/*", http.StripPrefix("/Images/", http.FileServer(http.Dir("./Images"))))
	goji.Serve()
}
示例#18
0
func (mux *Mux) Put(pattern web.PatternType, h handler) {
	goji.Put(pattern, func(c web.C, w http.ResponseWriter, r *http.Request) {
		mux.handleRequest(c, w, r, h)
	})
}
示例#19
0
func setup() {
	goji.Use(ContentSecurityPolicy(CSPOptions{
		policy: Config.contentSecurityPolicy,
		frame:  Config.xFrameOptions,
	}))

	if Config.noLogs {
		goji.Abandon(middleware.Logger)
	}

	// make directories if needed
	err := os.MkdirAll(Config.filesDir, 0755)
	if err != nil {
		log.Fatal("Could not create files directory:", err)
	}

	err = os.MkdirAll(Config.metaDir, 0700)
	if err != nil {
		log.Fatal("Could not create metadata directory:", err)
	}

	// ensure siteURL ends wth '/'
	if lastChar := Config.siteURL[len(Config.siteURL)-1:]; lastChar != "/" {
		Config.siteURL = Config.siteURL + "/"
	}

	// Template setup
	p2l, err := NewPongo2TemplatesLoader()
	if err != nil {
		log.Fatal("Error: could not load templates", err)
	}
	TemplateSet := pongo2.NewSet("templates", p2l)
	TemplateSet.Globals["sitename"] = Config.siteName
	err = populateTemplatesMap(TemplateSet, Templates)
	if err != nil {
		log.Fatal("Error: could not load templates", err)
	}

	staticBox = rice.MustFindBox("static")
	timeStarted = time.Now()
	timeStartedStr = strconv.FormatInt(timeStarted.Unix(), 10)

	// Routing setup
	nameRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)$`)
	selifRe := regexp.MustCompile(`^/selif/(?P<name>[a-z0-9-\.]+)$`)
	selifIndexRe := regexp.MustCompile(`^/selif/$`)
	torrentRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)/torrent$`)

	goji.Get("/", indexHandler)
	goji.Get("/paste/", pasteHandler)
	goji.Get("/paste", http.RedirectHandler("/paste/", 301))

	if Config.remoteUploads {
		goji.Get("/upload", uploadRemote)
		goji.Get("/upload/", uploadRemote)
	}

	goji.Post("/upload", uploadPostHandler)
	goji.Post("/upload/", uploadPostHandler)
	goji.Put("/upload", uploadPutHandler)
	goji.Put("/upload/:name", uploadPutHandler)
	goji.Delete("/:name", deleteHandler)

	goji.Get("/static/*", staticHandler)
	goji.Get("/favicon.ico", staticHandler)
	goji.Get("/robots.txt", staticHandler)
	goji.Get(nameRe, fileDisplayHandler)
	goji.Get(selifRe, fileServeHandler)
	goji.Get(selifIndexRe, unauthorizedHandler)
	goji.Get(torrentRe, fileTorrentHandler)
	goji.NotFound(notFoundHandler)
}
示例#20
0
func (ctr *Controller) RoutePut(rt *Route) {
	goji.Put(rt.Pattern, handlerWrap(rt))
}