示例#1
0
文件: server.go 项目: e154/mds-club
func Run(address string) {

	// routes
	r := pat.New()
	r.Get("/ws", wsHandler)
	r.Get("/js/", staticHandler)
	r.Get("/css/", staticHandler)
	r.Get("/images/", staticHandler)
	r.Get("/templates/", staticHandler)
	r.Get("/fonts/", staticHandler)
	r.Get("/api/authors/page~{page:[0-9]+}/limit~{limit:[0-9]+}/search={search:[а-яА-Яa-zA-Z0-9]*}", authorsFindHandler)
	r.Get("/api/authors/id~{id:[0-9]+}", authorGetByIdHandler)
	r.Get("/api/station/id~{id:[0-9]+}", stationHandler)
	r.Get("/api/books/id~{id:[0-9]+}", getBookHandler)
	r.Get("/api/books/page~{page:[0-9]+}/limit~{limit:[0-9]+}/author~{author}/search={search:[а-яА-Яa-zA-Z0-9]*}", booksHandler)
	r.Get("/api/file/list/book~{book:[0-9]+}", getBookFileListHandler)
	r.Post("/api/history/book~{book:[0-9]+}", addHistoryHandler)
	r.Get("/api/history/page~{page:[0-9]+}/limit~{limit:[0-9]+}", getHistoryHandler)
	r.Get("/", homeHandler)
	http.Handle("/", r)

	if err := http.ListenAndServe(address, nil); err != nil {
		fmt.Println(err.Error())
	}
}
示例#2
0
文件: server.go 项目: ranman/pluto
func main() {
	flag.Parse()

	var err error

	log.Print("Dialing mongodb database")
	mongodb_session, err = mgo.Dial(MONGODB_URL)
	if err != nil {
		panic(err)
	}
	log.Print("Succesfully dialed mongodb database")

	err = mongodb_session.DB(MONGODB_DATABASE).Login(MONGODB_USERNAME, MONGODB_PASSWORD)

	r := pat.New()
	//Create a unique index on 'guid', so that entires will not be duplicated
	//Any duplicate entries will be dropped silently when insertion is attempted
	guid_index := mgo.Index{
		Key:        []string{"guid"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	mongodb_session.DB(MONGODB_DATABASE).C(BLOGPOSTS_DB).EnsureIndex(guid_index)

	if *fetchposts {
		feeds, err := parseFeeds(FEEDS_LIST_FILENAME)
		if err != nil {
			panic(err)
		}

		for _, feed_info := range feeds {
			if len(feed_info) != 2 {
				panic(fmt.Errorf("Expect csv with 2 elements per row; received row with %d elements", len(feed_info)))
			}
			feed_url := feed_info[0]
			feed_author := feed_info[1]
			log.Printf("Found %s", feed_url)
			go func(uri string, author string) {
				scrapeRss(uri, author)
			}(feed_url, feed_author)
		}
	} else {
		log.Print("Skipping fetching posts - blog posts will NOT be updated")
	}

	//Order of routes matters
	//Routes *will* match prefixes
	http.Handle("/static/", http.FileServer(http.Dir("public")))
	r.Get("/feeds/all", serveFeeds)
	r.Get("/authors/all", serveAuthorInfo)
	r.Get("/", servePosts)
	//r.Get("/", serveHome)
	http.Handle("/", r)
	log.Printf("Starting HTTP server listening on %v", *httpAddr)
	if err := http.ListenAndServe(*httpAddr, nil); err != nil {
		log.Fatalf("Error listening, %v", err)
	}
}
示例#3
0
func main() {
	// Load config file
	cfg, err := config.Load()
	if err != nil {
		fmt.Println(err)
		return
	}

	// Instantiate logger
	logger, err := log.New(cfg.LogFile)
	if err != nil {
		fmt.Println(err)
		return
	}

	pool := image.NewImagePool(cfg.ImageDir)
	handlers := handler.New(pool, logger)

	router := pat.New()
	router.Get("/images/{uuid}/file", handlers.GetImageFile())
	router.Get("/images/{uuid}", handlers.GetImage())
	router.Get("/images", handlers.ListImages())
	router.Delete("/images/{uuid}", handlers.DeleteImage())
	router.Post("/images/{uuid}", handlers.ImageAction())
	router.Post("/images", handlers.CreateImage())
	router.Put("/images/{uuid}/file", handlers.AddImageFile())
	router.Get("/ping", handlers.Ping())
	http.Handle("/", router)

	fmt.Printf("Listening for http connections on %s\n", cfg.Listen)
	if err := http.ListenAndServe(cfg.Listen, nil); err != nil {
		fmt.Println(err)
	}
}
示例#4
0
func main() {
	err := SignatureCreateKey()
	if err != nil {
		log.Fatal("SignatureCreateKey: Is the Redis database running?: ", err)
		return
	}
	m := pat.New()
	m.Get("/static/{path}", http.HandlerFunc(StaticServer))
	m.Post("/setup", http.HandlerFunc(SetupHandler))
	m.Post("/user/key/{type}", http.HandlerFunc(SecretKeySetupHandler))

	// Control flow is: /authgh -> github -> /oauth2callbackgh
	m.Get("/authgh", http.HandlerFunc(AuthHandlerGH))
	m.Get("/oauth2callbackgh", http.HandlerFunc(Oauth2callbackHandlerGH))

	// Control flow is: /auth -> google -> /oauth2callback
	m.Get("/auth", http.HandlerFunc(authHandler))
	m.Get("/oauth2callback", http.HandlerFunc(oauth2callbackHandler))

	m.Get("/signout", http.HandlerFunc(signoutHandler))
	m.Post("/signout", http.HandlerFunc(signoutHandler))
	m.Post("/signature", http.HandlerFunc(SignatureVerifyHandler))
	http.Handle("/ws/glass/", websocket.Handler(WSGlassHandler))
	http.Handle("/ws/client", websocket.Handler(WSWebHandler))
	http.Handle("/ws/client/", websocket.Handler(WSWebHandler))
	http.Handle("/ws/web", websocket.Handler(WSWebHandler))
	http.Handle("/ws/web/", websocket.Handler(WSWebHandler))
	m.Get("/", http.HandlerFunc(PlaygroundServer))
	http.Handle("/", m)
	err = http.ListenAndServe(":"+servePort, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#5
0
func TestExecEarlyExit(test *testing.T) {
	config.ServerURI = "127.0.0.1:1236"

	mux := pat.New()
	normalPing(mux)
	normalExec(test, mux)
	listen := startServer(test, mux)
	defer listen.Close()

	errChan := make(chan error)
	go func() {
		// need to use a pipe so that no EOF is returned. this was causing test to fail very quickly
		r, _ := io.Pipe()
		out := &bytes.Buffer{}
		err := execInternal("exec", "cmd=exit", r, out)
		test.Log("exited", err)
		if err != nil {
			errChan <- err
			return
		}
		close(errChan)
	}()
	select {
	case <-time.After(time.Second * 4):
		test.Log("timed out...")
		test.FailNow()
	case err := <-errChan:
		if err == nil {
			return
		}
		test.Log(err)
		test.FailNow()
	}
}
示例#6
0
文件: api.go 项目: nanopack/pulse
// registerRoutes
func registerRoutes() (*pat.Router, error) {
	lumber.Debug("[PULSE :: API] Registering routes...")

	//
	router := pat.New()

	//
	router.Get("/ping", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("pong"))
	})

	router.Options("/", cors)

	router.Get("/keys", keysRequest)
	router.Get("/tags", tagsRequest)

	router.Get("/latest/{stat}", doCors(latestStat))
	router.Get("/hourly/{stat}", doCors(hourlyStat))
	router.Get("/daily/{stat}", doCors(dailyStat))
	router.Get("/daily_peaks/{stat}", doCors(dailyStat))

	// only expose alert routes if alerting configured
	if viper.GetString("kapacitor-address") != "" {
		// todo: maybe get and list tasks from kapacitor
		router.Post("/alerts", doCors(setAlert))
		router.Put("/alerts", doCors(setAlert))
		router.Delete("/alerts/{id}", doCors(deleteAlert))
	}

	return router, nil
}
示例#7
0
文件: api.go 项目: nanopack/portal
func routes() *pat.Router {
	router := pat.New()
	// balancing
	router.Delete("/services/{svcId}/servers/{srvId}", deleteServer)
	router.Get("/services/{svcId}/servers/{srvId}", getServer)
	router.Put("/services/{svcId}/servers", putServers)
	router.Post("/services/{svcId}/servers", postServer)
	router.Get("/services/{svcId}/servers", getServers)
	router.Delete("/services/{svcId}", deleteService)
	router.Put("/services/{svcId}", putService)
	router.Get("/services/{svcId}", getService)
	router.Post("/services", postService)
	router.Put("/services", putServices)
	router.Get("/services", getServices)

	// routing
	router.Delete("/routes", deleteRoute)
	router.Put("/routes", putRoutes)
	router.Get("/routes", getRoutes)
	router.Post("/routes", postRoute)

	// certificates
	router.Delete("/certs", deleteCert)
	router.Put("/certs", putCerts)
	router.Get("/certs", getCerts)
	router.Post("/certs", postCert)

	// ips
	router.Delete("/vips", deleteVip)
	router.Put("/vips", putVips)
	router.Get("/vips", getVips)
	router.Post("/vips", postVip)

	return router
}
示例#8
0
func main() {
	list := NewList()
	gcmPusher := NewGCMPusher(*gcmKey)
	wsPusher := NewWSPusher()
	bus := NewEventBus([]Subscriber{gcmPusher, wsPusher})

	r := pat.New()
	corsHandler := CORSHandler()

	r.Get("/list", IndexHandler(list))
	r.Add("OPTIONS", "/list", corsHandler)
	r.Put("/list/{urn}", SetHandler(list, bus))
	r.Add("OPTIONS", "/list/{urn}", corsHandler)
	r.Post("/list/{urn}/{action:(play|pause)}", PlaybackHandler(list, bus))
	r.Add("OPTIONS", "/list/{urn}/{action:(play|pause)}", corsHandler)
	r.Delete("/list/{urn}", DeleteHandler(list, bus))
	r.Add("OPTIONS", "/list/{urn}", corsHandler)
	r.Handle("/subscribe/gcm", GCMSubscriptionHandler(gcmPusher))
	r.Handle("/subscribe/ws", WSSubscriptionHandler(wsPusher))

	err := http.ListenAndServe(*listen, r)
	if err != nil {
		log.Fatal(err)
	}
}
示例#9
0
func launchServer(flag *flag.Flag) error {
	path, err := config.GetString("assets")
	if err != nil {
		return errors.New("No assets folder specified in config file.")
	}

	scheduler.Run()

	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(path))))

	r := pat.New()

	r.Post("/schedules/{scheduleId}", updateSchedule)
	r.Get("/schedules/{scheduleId}/edit", editSchedule)
	r.Get("/schedules/new", newSchedule)
	r.Post("/schedules", createSchedule)

	r.Get("/valves/{valveId}/edit", editValve)
	r.Get("/valves/{valveId}/open", openValve)
	r.Get("/valves/{valveId}/close", closeValve)
	r.Post("/valves/{valveId}", updateValve)
	r.Get("/valves/{valveId}", showValve)

	r.Get("/manual", manual)
	r.Get("/", homepage)

	http.Handle("/", r)

	initializeTemplates(path)

	err = http.ListenAndServe(":7777", nil)

	return err

}
示例#10
0
文件: api.go 项目: nanopack/sherpa
// registerRoutes registers all api routes with the router
func registerRoutes() (*pat.Router, error) {
	config.Log.Debug("[sherpa/api] Registering routes...\n")

	//
	router := pat.New()

	//
	router.Get("/ping", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("pong"))
	})

	// templates
	router.Delete("/templates/{id}", handleRequest(deleteTemplate))
	router.Get("/templates/{id}", handleRequest(getTemplate))
	router.Post("/templates", handleRequest(postTemplate))
	router.Get("/templates", handleRequest(getTemplates))

	// builds
	router.Delete("/builds/{id}", handleRequest(deleteBuild))
	router.Get("/builds/{id}", handleRequest(getBuild))
	router.Post("/builds", handleRequest(postBuild))
	router.Get("/builds", handleRequest(getBuilds))

	return router, nil
}
示例#11
0
文件: willy_test.go 项目: Isted/going
func App() http.Handler {
	p := pat.New()
	p.Get("/get", func(res http.ResponseWriter, req *http.Request) {
		res.WriteHeader(201)
		fmt.Fprintln(res, "METHOD:"+req.Method)
		fmt.Fprint(res, "Hello from Get!")
	})
	p.Delete("/delete", func(res http.ResponseWriter, req *http.Request) {
		res.WriteHeader(201)
		fmt.Fprintln(res, "METHOD:"+req.Method)
		fmt.Fprint(res, "Goodbye")
	})
	p.Post("/post", func(res http.ResponseWriter, req *http.Request) {
		fmt.Fprintln(res, "METHOD:"+req.Method)
		fmt.Fprint(res, "NAME:"+req.PostFormValue("name"))
	})
	p.Put("/put", func(res http.ResponseWriter, req *http.Request) {
		fmt.Fprintln(res, "METHOD:"+req.Method)
		fmt.Fprint(res, "NAME:"+req.PostFormValue("name"))
	})
	p.Post("/sessions/set", func(res http.ResponseWriter, req *http.Request) {
		sess, _ := Store.Get(req, "my-session")
		sess.Values["name"] = req.PostFormValue("name")
		sess.Save(req, res)
	})
	p.Get("/sessions/get", func(res http.ResponseWriter, req *http.Request) {
		sess, _ := Store.Get(req, "my-session")
		if sess.Values["name"] != nil {
			fmt.Fprint(res, "NAME:"+sess.Values["name"].(string))
		}
	})
	return p
}
func GetRouter() *pat.Router {
	r := pat.New()

	r.Get("/mail/healthcheck", HelloWorldHandler)
	r.Post("/mail/contactus", ContactUsHandler)
	return r
}
示例#13
0
// Listen binds to httpBindAddr
func Listen(httpBindAddr string, Asset func(string) ([]byte, error), exitCh chan int, registerCallback func(http.Handler)) {
	log.Info("[HTTP] Binding to address: %s", httpBindAddr)

	pat := pat.New()
	registerCallback(pat)

	f := func(w http.ResponseWriter, req *http.Request) {
		if Authorised == nil {
			pat.ServeHTTP(w, req)
			return
		}

		u, pw, ok := req.BasicAuth()
		if !ok || !Authorised(u, pw) {
			w.Header().Set("WWW-Authenticate", "Basic")
			w.WriteHeader(401)
			return
		}
		pat.ServeHTTP(w, req)
	}

	err := http.ListenAndServe(httpBindAddr, http.HandlerFunc(f))
	if err != nil {
		log.Fatalf("[HTTP] Error binding to address %s: %s", httpBindAddr, err)
	}
}
示例#14
0
func main() {
	SignatureCreateKey()
	m := pat.New()
	m.Get("/static/{path}", http.HandlerFunc(StaticServer))
	m.Post("/notify/{key}", http.HandlerFunc(NotifyServer))
	m.Post("/notify/", http.HandlerFunc(NotifyServer))
	m.Post("/setup", http.HandlerFunc(SetupHandler))
	m.Post("/user/key/{type}", http.HandlerFunc(SecretKeySetupHandler))

	// Control flow is: /auth -> google -> /oauth2callback
	m.Get("/auth", http.HandlerFunc(authHandler))
	m.Get("/oauth2callback", http.HandlerFunc(oauth2callbackHandler))

	m.Post("/signout", http.HandlerFunc(signoutHandler))
	m.Post("/flags", http.HandlerFunc(FlagsHandler))
	m.Get("/flags", http.HandlerFunc(FlagsHandler))
	m.Delete("/flags", http.HandlerFunc(FlagsHandler))
	m.Post("/signature", http.HandlerFunc(SignatureVerifyHandler))
	http.Handle("/ws/glass/", websocket.Handler(WSGlassHandler))
	http.Handle("/ws/web", websocket.Handler(WSWebHandler))
	http.Handle("/ws/web/", websocket.Handler(WSWebHandler))
	m.Get("/", http.HandlerFunc(PlaygroundServer))
	http.Handle("/", m)
	err := http.ListenAndServe(":"+servePort, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#15
0
文件: main.go 项目: bentranter/id
func main() {
	// Initialize any provider
	provider := google.New()

	// Bare http
	http.Handle("/auth/google/authorize", id.Authorize(provider))
	http.Handle("/auth/google/callback", id.Callback(provider, "auth/restricted"))
	http.Handle("/auth/restricted", id.Middleware(id.Verify, id.Verified))

	// Default mux
	serveMux := http.NewServeMux()
	serveMux.Handle("/auth/google/authorize", id.Authorize(provider))
	serveMux.Handle("/auth/google/callback", id.Callback(provider, "auth/restricted"))
	serveMux.Handle("/auth/restricted", id.Middleware(id.Verify, id.Verified))

	// Gorilla's Pat. Requires type assertion.
	p := pat.New()
	p.Get("/auth/google/authorize", id.Authorize(provider).(http.HandlerFunc))
	p.Get("/auth/google/callback", id.Callback(provider, "auth/restricted").(http.HandlerFunc))

	// Gorilla's Mux
	m := mux.NewRouter()
	m.Handle("/auth/google/authorize", id.Authorize(provider))
	m.Handle("/auth/google/callback", id.Callback(provider, "auth/restricted"))

	// Julien Schmidt's httprouter
	r := httprouter.New()
	r.GET("/httprouter/auth/google/authorize", id.HTTPRouterAuthorize(provider))
	r.GET("/httprouter/auth/google/callback", id.HTTPRouterCallback(provider, "auth/restricted"))

	log.Printf("Serving HTTP on port 3000")
	log.Fatal(http.ListenAndServe(":3000", serveMux))
}
示例#16
0
func main() {
	flag.Parse()

	err := godotenv.Load(fmt.Sprintf("config/%s.env", *env))
	if err != nil {
		log.Fatal(err)
		return
	}

	goth.UseProviders(
		github.New(os.Getenv("GITHUB_CLIENT_KEY"), os.Getenv("GITHUB_SECRET"), os.Getenv("GITHUB_CALLBACK")),
	)

	p := pat.New()

	r := newRoom()
	r.tracer = trace.New(os.Stdout)
	p.Add("GET", "/chat", MustAuth(&templateHandler{filename: "chat.html"}))
	p.Add("GET", "/login", &templateHandler{filename: "login.html"})
	p.Get("/auth/{action}/{provider}", loginHandler)
	p.Add("GET", "/room", r)

	// チャットルームの開始
	go r.run()
	// Webサーバの起動
	log.Println("Webサーバーを開始します。ポート: ", *addr)
	if err := http.ListenAndServe(*addr, p); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
示例#17
0
文件: main_test.go 项目: umsatz/ent
func TestHandleCreateInvalidBucket(t *testing.T) {
	fs := ent.NewMemoryFS()

	r := pat.New()
	r.Post(ent.RouteFile, handleCreate(ent.NewMemoryProvider(), fs))

	ts := httptest.NewServer(r)
	defer ts.Close()

	ep := fmt.Sprintf("%s/%s/%s", ts.URL, "fake-bucket", "cat.zip")
	res, err := http.Post(ep, "text/plain", bytes.NewReader([]byte("fake file")))
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()

	resp := ent.ResponseError{}
	err = json.NewDecoder(res.Body).Decode(&resp)
	if err != nil {
		t.Fatal(err)
	}

	if res.StatusCode != http.StatusNotFound {
		t.Errorf("HTTP %d", res.StatusCode)
	}
}
示例#18
0
文件: main.go 项目: yageek/apiversion
func ApiV1() *apiversion.Version {

	r := pat.New()
	r.Get("/", HandlerV1)

	return apiversion.NewVersion("v1", r)
}
示例#19
0
文件: main_test.go 项目: umsatz/ent
func TestHandleBucketList(t *testing.T) {
	var (
		bs = createBuckets([]string{"peer", "nxt", "master"})
		r  = pat.New()
	)

	r.Get("/", handleBucketList(ent.NewMemoryProvider(bs...)))

	ts := httptest.NewServer(r)
	defer ts.Close()

	res, err := http.Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()

	resp := ent.ResponseBucketList{}
	err = json.NewDecoder(res.Body).Decode(&resp)
	if err != nil {
		t.Fatal(err)
	}

	if res.StatusCode != http.StatusOK {
		t.Errorf("HTTP %d", res.StatusCode)
	}

	if resp.Count != len(bs) {
		t.Errorf("not enough buckets returned: %d != %d", resp.Count, len(bs))
	}

	if !reflect.DeepEqual(toMap(resp.Buckets), toMap(bs)) {
		t.Errorf("wrong answer")
	}
}
示例#20
0
func SetupRouter() *pat.Router {
	router := pat.New()
	router.Post("/user/{name}/key", http.HandlerFunc(addKey))
	router.Delete("/user/{name}/key/{keyname}", http.HandlerFunc(removeKey))
	router.Get("/user/{name}/keys", http.HandlerFunc(listKeys))
	router.Post("/user", http.HandlerFunc(newUser))
	router.Delete("/user/{name}", http.HandlerFunc(removeUser))
	router.Delete("/repository/revoke", http.HandlerFunc(revokeAccess))
	router.Get("/repository/{name:[^/]*/?[^/]+}/archive", http.HandlerFunc(getArchive))
	router.Get("/repository/{name:[^/]*/?[^/]+}/contents", http.HandlerFunc(getFileContents))
	router.Get("/repository/{name:[^/]*/?[^/]+}/tree", http.HandlerFunc(getTree))
	router.Get("/repository/{name:[^/]*/?[^/]+}/branches", http.HandlerFunc(getBranches))
	router.Get("/repository/{name:[^/]*/?[^/]+}/tags", http.HandlerFunc(getTags))
	router.Get("/repository/{name:[^/]*/?[^/]+}/diff/commits", http.HandlerFunc(getDiff))
	router.Post("/repository/{name:[^/]*/?[^/]+}/commit", http.HandlerFunc(commit))
	router.Get("/repository/{name:[^/]*/?[^/]+}/logs", http.HandlerFunc(getLogs))
	router.Post("/repository/grant", http.HandlerFunc(grantAccess))
	router.Post("/repository", http.HandlerFunc(newRepository))
	router.Get("/repository/{name:[^/]*/?[^/]+}", http.HandlerFunc(getRepository))
	router.Delete("/repository/{name:[^/]*/?[^/]+}", http.HandlerFunc(removeRepository))
	router.Put("/repository/{name:[^/]*/?[^/]+}", http.HandlerFunc(updateRepository))
	router.Get("/healthcheck", http.HandlerFunc(healthCheck))
	router.Post("/hook/{name}", http.HandlerFunc(addHook))
	return router
}
示例#21
0
文件: ent.go 项目: queer1/ent
func main() {
	var (
		fsRoot      = flag.String("fs.root", "/tmp", "FileSystem root directory")
		httpAddress = flag.String("http.addr", ":5555", "HTTP listen address")
		providerDir = flag.String("provider.dir", "/tmp", "Provider directory with bucket policies")
	)
	flag.Parse()

	prometheus.Register("ent_requests_total", "Total number of requests made", prometheus.NilLabels, requestTotal)
	prometheus.Register("ent_requests_duration_nanoseconds_total", "Total amount of time ent has spent to answer requests in nanoseconds", prometheus.NilLabels, requestDuration)
	prometheus.Register("ent_requests_duration_nanoseconds", "Amounts of time ent has spent answering requests in nanoseconds", prometheus.NilLabels, requestDurations)
	prometheus.Register("ent_request_bytes_total", "Total volume of request payloads emitted in bytes", prometheus.NilLabels, requestBytes)
	prometheus.Register("ent_response_bytes_total", "Total volume of response payloads emitted in bytes", prometheus.NilLabels, responseBytes)

	p, err := NewDiskProvider(*providerDir)
	if err != nil {
		log.Fatal(err)
	}

	fs := NewDiskFS(*fsRoot)
	r := pat.New()
	r.Get(fileRoute, handleGet(p, fs))
	r.Post(fileRoute, handleCreate(p, fs))
	r.Handle("/metrics", prometheus.DefaultRegistry.Handler())
	r.Get("/", handleBucketList(p))

	log.Fatal(http.ListenAndServe(*httpAddress, http.Handler(r)))
}
示例#22
0
文件: api.go 项目: nanopack/logvac
// Start starts the web server with the logvac functions
func Start(collector http.HandlerFunc) error {
	retriever := GenerateArchiveEndpoint(drain.Archiver)

	router := pat.New()

	router.Get("/add-token", handleRequest(addKey))
	router.Get("/remove-token", handleRequest(removeKey))
	router.Add("OPTIONS", "/", handleRequest(cors))

	router.Post("/logs", verify(handleRequest(collector)))
	router.Get("/logs", verify(handleRequest(retriever)))

	cert, _ := nanoauth.Generate("nanobox.io")
	auth := nanoauth.Auth{
		Header:      "X-AUTH-TOKEN",
		Certificate: cert,
	}

	// blocking...
	if config.Insecure {
		config.Log.Info("Api Listening on http://%s...", config.ListenHttp)
		return auth.ListenAndServe(config.ListenHttp, config.Token, router, "/logs")
	}

	config.Log.Info("Api Listening on https://%s...", config.ListenHttp)
	return auth.ListenAndServeTLS(config.ListenHttp, config.Token, router, "/logs")
}
示例#23
0
//start server
func startServer() {
	r := pat.New()
	r.Get("/news/{uf:[A-Za-z]+}", requestPageDB)
	http.Handle("/", r)
	http.Handle("/CSS/", http.StripPrefix("/CSS/", http.FileServer(http.Dir("templates/CSS"))))
	http.ListenAndServe(":"+os.Getenv("PORT"), nil)
}
示例#24
0
func registerRoutes() *pat.Router {
	router := pat.New()

	router.Put("/public/objects/{id}", handleRequest(setObjectPublic))
	router.Get("/info/objects/{id}", handleRequest(getObjectInfo))
	router.Post("/objects", handleRequest(createObject))
	router.Add("HEAD", "/objects/{id}", handleRequest(getObjectInfo))
	router.Get("/objects/{id}", handleRequest(getObject))
	router.Put("/objects/{id}", handleRequest(replaceObject))
	router.Get("/objects", handleRequest(listObjects))
	router.Delete("/objects/{id}", handleRequest(deleteObject))

	router.Post("/buckets", handleRequest(createBucket))
	router.Get("/buckets/{id}", handleRequest(getBucket))
	router.Get("/buckets", handleRequest(listBuckets))
	router.Delete("/buckets/{id}", handleRequest(deleteBucket))

	// admin only
	router.Get("/users", handleRequest(adminAccess(listUsers)))
	router.Post("/users", handleRequest(adminAccess(createUser)))
	router.Delete("/users/{id}", handleRequest(adminAccess(deleteUser)))

	router.Get("/{user}/{bucket}/{id}", handleRequest(getPublicObject))

	router.Get("/", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("привет мир"))
	})

	return router
}
示例#25
0
func webserver() {
	//kill channel to programatically
	killch := make(chan os.Signal, 1)
	signal.Notify(killch, os.Interrupt)
	signal.Notify(killch, syscall.SIGTERM)
	signal.Notify(killch, syscall.SIGINT)
	signal.Notify(killch, syscall.SIGQUIT)
	go func() {
		<-killch
		LOG.Fatalf("Interrupt %s", time.Now().String())
	}()

	httphost := "localhost"
	httpport := "8080"

	//we need to start 2 servers, http for status and zmq
	wg := &sync.WaitGroup{}
	wg.Add(1)
	//first start http interface for self stats
	go func() {
		r := pat.New()
		r.Get("/main/{type}/{hcids}", http.HandlerFunc(mainHandle))
		http.Handle("/", r)

		LOG.Debug("Listening %s : %s", httphost, httpport)
		err := http.ListenAndServe(httphost+":"+httpport, nil)
		if err != nil {
			LOG.Fatalf("ListenAndServe: %s", err)
		}
		wg.Done()
	}()

	wg.Wait()
}
示例#26
0
func mockTwitter(f func(*httptest.Server)) {
	p := pat.New()
	p.Get("/oauth/request_token", func(res http.ResponseWriter, req *http.Request) {
		fmt.Fprint(res, "oauth_token=TOKEN&oauth_token_secret=SECRET")
	})
	p.Get("/1.1/account/verify_credentials.json", func(res http.ResponseWriter, req *http.Request) {
		data := map[string]string{
			"name":              "Homer",
			"screen_name":       "duffman",
			"description":       "Duff rules!!",
			"profile_image_url": "http://example.com/image.jpg",
			"id_str":            "1234",
			"location":          "Springfield",
		}
		json.NewEncoder(res).Encode(&data)
	})
	ts := httptest.NewServer(p)
	defer ts.Close()

	originalRequestURL := requestURL
	originalEndpointProfile := endpointProfile

	requestURL = ts.URL + "/oauth/request_token"
	endpointProfile = ts.URL + "/1.1/account/verify_credentials.json"

	f(ts)

	requestURL = originalRequestURL
	endpointProfile = originalEndpointProfile
}
示例#27
0
func init() {
	r := pat.New()
	r.Add("GET", `/course/list`, handlerInstructor(course_list))
	r.Add("GET", `/course/grades/{coursetag:[\w:_\-]+$}`, handlerInstructor(course_grades))
	r.Add("POST", `/course/newassignment/{coursetag:[\w:_\-]+$}`, handlerInstructorJson(course_newassignment))
	r.Add("POST", `/course/courselistupload/{coursetag:[\w:_\-]+$}`, handlerInstructorJson(course_courselistupload))
	http.Handle("/course/", r)
}
示例#28
0
文件: main_test.go 项目: umsatz/ent
func TestHandleFileList(t *testing.T) {
	var (
		name = "master"
		bs   = createBuckets([]string{name})
		fs   = ent.NewMemoryFS()
		p    = "list/files"
		r    = pat.New()
	)

	r.Get(ent.RouteBucket, handleFileList(ent.NewMemoryProvider(bs...), fs))

	ts := httptest.NewServer(r)
	defer ts.Close()

	f, err := os.Open(fixtureZip)
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 10; i++ {
		_, err := fs.Create(bs[0], fmt.Sprintf("%s/%d", p, i), f)
		if err != nil {
			t.Fatal(err)
		}
	}

	inputs := []struct {
		count int
		vs    url.Values
	}{
		{
			count: 1,
			vs:    url.Values{"limit": []string{"1"}, "sort": []string{"+lastModified"}},
		},
		{
			count: 10,
			vs:    url.Values{"prefix": []string{p}},
		},
		{
			count: 4,
			vs:    url.Values{"limit": []string{"4"}, "prefix": []string{p}, "sort": []string{"-key"}},
		},
	}

	for _, input := range inputs {
		filesURL := fmt.Sprintf("%s/%s?%s", ts.URL, name, input.vs.Encode())

		files, err := getFiles(filesURL)
		if err != nil {
			t.Error(err)
		}

		if have, want := len(files), input.count; have != want {
			t.Logf("%#v", files)
			t.Errorf("have %d, want %d", have, want)
		}
	}
}
示例#29
0
func main() {
	r := pat.New()
	r.Get("/multiget", MultigetHandler)
	http.Handle("/", r)
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
示例#30
0
func init() {
	r := pat.New()
	r.Add("GET", `/student/courses`, handlerStudent(student_courses))
	r.Add("GET", `/student/assignment/{id:\d+$}`, handlerStudent(student_assignment))
	r.Add("GET", `/student/submission/{id:\d+}/{n:\d+$}`, handlerStudent(student_assignment))
	r.Add("GET", `/student/download/{id:\d+$}`, handlerStudent(student_download))
	r.Add("POST", `/student/submit/{id:\d+$}`, handlerStudentJson(student_submit))
	http.Handle("/student/", r)
}