Esempio n. 1
0
func main() {
	boneSub := bone.New()
	gorrilaSub := mux.NewRouter()
	httprouterSub := httprouter.New()

	boneSub.GetFunc("/test", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("Hello from bone mux"))
	})

	gorrilaSub.HandleFunc("/test", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("Hello from gorilla mux"))
	})

	httprouterSub.GET("/test", func(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
		rw.Write([]byte("Hello from httprouter mux"))
	})

	muxx := bone.New().Prefix("/api")

	muxx.SubRoute("/bone", boneSub)
	muxx.SubRoute("/gorilla", gorrilaSub)
	muxx.SubRoute("/http", httprouterSub)

	http.ListenAndServe(":8080", muxx)
}
Esempio n. 2
0
func main() {

	db, err := bolt.Open("proxy.db", 0600, nil)

	if err != nil {
		log.Fatal("Fatal: %s\n", err.Error())
	}

	defer db.Close()

	adminServer := proxyAdminServer{db}

	adminMux := bone.New()
	adminMux.Get("/proxy", http.HandlerFunc(adminServer.GetProxies))
	adminMux.Delete("/proxy/:id", http.HandlerFunc(adminServer.DeleteProxyIteraction))
	adminMux.Post("/proxy", http.HandlerFunc(adminServer.NewProxyIteraction))

	proxyServer := proxyServer{&http.Client{}, db}

	mux := bone.New()

	mux.Handle("/*", http.HandlerFunc(proxyServer.ProxyHandler))

	go func(port string) {
		log.Println("Starting admin server")
		log.Fatal(http.ListenAndServe(port, adminMux))
	}(":9080")
	log.Println("Starting test proxy")
	log.Fatal(http.ListenAndServe(":9090", mux))
}
Esempio n. 3
0
func main() {
	mux := bone.New()

	mux.GetFunc("/ctx/:var", rootHandler)

	http.ListenAndServe(":8080", mux)
}
Esempio n. 4
0
// getBoneRouter returns mux for admin interface
func getBoneRouter(d DBClient) *bone.Mux {
	mux := bone.New()

	mux.Get("/records", http.HandlerFunc(d.AllRecordsHandler))
	mux.Delete("/records", http.HandlerFunc(d.DeleteAllRecordsHandler))
	mux.Post("/records", http.HandlerFunc(d.ImportRecordsHandler))

	mux.Get("/count", http.HandlerFunc(d.RecordsCount))
	mux.Get("/stats", http.HandlerFunc(d.StatsHandler))
	mux.Get("/statsws", http.HandlerFunc(d.StatsWSHandler))

	mux.Get("/state", http.HandlerFunc(d.CurrentStateHandler))
	mux.Post("/state", http.HandlerFunc(d.StateHandler))

	if d.Cfg.Development {
		// since hoverfly is not started from cmd/hoverfly/hoverfly
		// we have to target to that directory
		log.Warn("Hoverfly is serving files from /static/dist instead of statik binary!")
		mux.Handle("/*", http.FileServer(http.Dir("../../static/dist")))
	} else {
		// preparing static assets for embedded admin
		statikFS, err := fs.New()

		if err != nil {
			log.WithFields(log.Fields{
				"Error": err.Error(),
			}).Error("Failed to load statikFS, admin UI might not work :(")
		}

		mux.Handle("/*", http.FileServer(statikFS))
	}

	return mux
}
Esempio n. 5
0
// NewServer creates a server that will listen for requests over HTTP and interact with the RCON server specified
// non-/api prefixed routes are served from static files compiled into bindata_assetfs.go
func NewRestServer(c *ServerConfig) {
	var err error
	rcon_client, err = mcrcon.NewClient(c.RCON_address, c.RCON_port, c.RCON_password)

	if err != nil {
		panic(fmt.Errorf("Could not connect to RCON server at %s:%d. (Error was: %s)", c.RCON_address, c.RCON_port, err))
	}

	router := bone.New()

	// Redirect static resources, and then handle the static resources (/gui/) routes with the static asset file
	router.Handle("/", http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		http.Redirect(response, request, "/gui/", 302)
	}))
	router.Get("/gui/", http.StripPrefix("/gui/", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: ""})))

	// Define the API (JSON) routes
	router.GetFunc("/api", apiRootHandler)
	router.GetFunc("/api/users", usersRootHandler)
	router.GetFunc("/api/users/:username", usernameHandler)

	// TODO: Require a http basic auth username and password if passed in.

	// Start the server
	fmt.Println("Starting server on port", c.Port)
	http.ListenAndServe(fmt.Sprintf(":%d", c.Port), router)
}
Esempio n. 6
0
func main() {
	db, err := sql.Open("postgres", "user=laptop dbname=estelle_test sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}

	r := render.New(render.Options{
		Directory:  "views",
		Extensions: []string{".html"},
	})

	mux := bone.New()
	ServeResource := assets.ServeResource
	mux.HandleFunc("/img/", ServeResource)
	mux.HandleFunc("/css/", ServeResource)
	mux.HandleFunc("/js/", ServeResource)

	mux.HandleFunc("/pages", func(w http.ResponseWriter, req *http.Request) {
		rows, err := db.Query("SELECT id, title FROM pages")
		if err != nil {
			log.Fatal(err)
		}
		defer rows.Close()
		type yourtype struct {
			Id    int
			Title string
		}

		s := []yourtype{}
		for rows.Next() {
			var t yourtype
			if err := rows.Scan(&t.Id, &t.Title); err != nil {
				log.Fatal(err)
			}
			fmt.Printf("%s", t.Title)
			s = append(s, t)
		}
		r.HTML(w, http.StatusOK, "foofoo", s)
	})

	mux.HandleFunc("/bar", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "bar", nil)
	})

	mux.HandleFunc("/home/:id", func(w http.ResponseWriter, req *http.Request) {
		id := bone.GetValue(req, "id")
		r.HTML(w, http.StatusOK, "index", id)
	})

	mux.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "foo", nil)
	})

	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "index", nil)
	})

	http.ListenAndServe(":8080", mux)
}
Esempio n. 7
0
func main() {
	mux := bone.New()

	mux.GetFunc("/image/:rows", ImageHandler)
	mux.GetFunc("/html/:rows", HtmlHandler)

	http.ListenAndServe(":3000", mux)
}
Esempio n. 8
0
func getBoneRouter(h HTTPClientHandler) *bone.Mux {
	mux := bone.New()
	mux.Get("/query", http.HandlerFunc(h.queryTwitter))
	mux.Get("/", http.HandlerFunc(h.homeHandler))
	// handling static files
	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	return mux
}
Esempio n. 9
0
func main() {
	router := bone.New()

	router.GetFunc("/", index)
	router.GetFunc("/hello/:name", hello)

	log.Println("Starting server on port 9090")
	log.Fatal(http.ListenAndServe(":9090", router))
}
Esempio n. 10
0
func main() {
	// looking for option args when starting App
	// like ./overeer -port=":3000" would start on port 3000
	var port = flag.String("port", ":3000", "Server port")
	var dbActions = flag.String("db", "", "Database actions - create, migrate, drop")
	flag.Parse() // parse the flag

	// init connection
	db, err := gorm.Open("sqlite3", "gorm.db")
	if err != nil {
		log.WithFields(log.Fields{"error": err.Error()}).Fatal("Failed to open sqlite DB")
	}
	defer db.Close()
	db.DB()
	db.DB().Ping()
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	// flag to do something with the database
	if *dbActions != "" {
		log.WithFields(log.Fields{"action": dbActions}).Info("Database action initiated.")
		d := DBActions{db: &db}

		// create tables
		if *dbActions == "create" {
			d.createTables()
		}
		// drop tables
		if *dbActions == "drop" {
			d.dropTables()
		}
		return
	}
	r := render.New(render.Options{Layout: "layout"})
	h := DBHandler{db: &db, r: r}

	mux := bone.New()
	mux.Get("/", http.HandlerFunc(homeHandler))
	mux.Post("/stubos", http.HandlerFunc(h.stubosCreateHandler))
	mux.Get("/stubos", http.HandlerFunc(h.stuboShowHandler))
	mux.Delete("/stubos/:id", http.HandlerFunc(h.stuboDestroyHandler))
	mux.Get("/stubos/:id", http.HandlerFunc(h.stuboDetailedHandler))
	mux.Get("/stubos/:id/scenarios/:scenario", http.HandlerFunc(h.scenarioDetailedHandler))
	mux.Get("/stubos/:id/scenarios/:scenario/stubs", http.HandlerFunc(h.scenarioStubsHandler))
	// handling static files
	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	n := negroni.Classic()
	n.Use(negronilogrus.NewMiddleware())
	n.UseHandler(mux)

	log.WithFields(log.Fields{
		"port": port,
	}).Info("Overseer is starting")

	n.Run(*port)
}
Esempio n. 11
0
func init() {
	mux := bone.New()

	mux.PostFunc("/buy_request", BuyRequestHandler)
	mux.GetFunc("/request/:key", RequestHandler)
	mux.GetFunc("/delivery_status/:key", DeliveryHandler)
	mux.PostFunc("/accept_request/:key", AcceptRequestHandler)
	mux.PostFunc("/get_cl", GetCL)
	http.Handle("/", mux)
}
Esempio n. 12
0
func main() {
	mux := bone.New()

	mux.GetFunc("/", defaultHandler)
	mux.GetFunc("/reg/#var^[a-z]$/#var2^[0-9]$", ShowVar)
	mux.GetFunc("/test", defaultHandler)
	mux.Get("/file/", http.StripPrefix("/file/", http.FileServer(http.Dir("assets"))))

	http.ListenAndServe(":8080", mux)
}
Esempio n. 13
0
func runServer() error {
	mux := bone.New()
	mux.HandleFunc("/", inputs)
	mux.HandleFunc("/api/", serveArticle)

	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	err := http.ListenAndServe(*listenAddr, httpLogger(mux))

	return err
}
Esempio n. 14
0
func init() {
	mux := bone.New()

	mux.GetFunc("/image/:rows", ImageHandler)
	mux.GetFunc("/html/:rows", HtmlHandler)
	mux.GetFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "http://github.com/matthewdu/rule110-go", 301)
	})

	http.Handle("/", mux)
}
Esempio n. 15
0
func getBoneRouter(h HTTPClientHandler) *bone.Mux {
	mux := bone.New()
	mux.Get("/1.1/search/tweets.json", http.HandlerFunc(h.tweetSearchEndpoint))
	mux.Get("/admin", http.HandlerFunc(h.adminHandler))
	mux.Post("/admin/state", http.HandlerFunc(h.stateHandler))
	mux.Get("/admin/state", http.HandlerFunc(h.getStateHandler))
	// handling static files
	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	return mux
}
Esempio n. 16
0
// getBoneRouter returns mux for admin interface
func (this *AdminApi) getBoneRouter(d *Hoverfly) *bone.Mux {
	mux := bone.New()

	authHandler := &handlers.AuthHandler{
		d.Authentication,
		d.Cfg.SecretKey,
		d.Cfg.JWTExpirationDelta,
		d.Cfg.AuthEnabled,
	}

	authHandler.RegisterRoutes(mux)

	handlers := GetAllHandlers(d)
	for _, handler := range handlers {
		handler.RegisterRoutes(mux, authHandler)
	}

	if d.Cfg.Development {
		// since hoverfly is not started from cmd/hoverfly/hoverfly
		// we have to target to that directory
		log.Warn("Hoverfly is serving files from /static/admin/dist instead of statik binary!")
		mux.Handle("/js/*", http.StripPrefix("/js/", http.FileServer(http.Dir("../../static/admin/dist/js"))))

		mux.HandleFunc("/*", func(w http.ResponseWriter, r *http.Request) {
			http.ServeFile(w, r, "../../static/admin/dist/index.html")
		})

	} else {
		// preparing static assets for embedded admin
		statikFS, err := fs.New()

		if err != nil {
			log.WithFields(log.Fields{
				"Error": err.Error(),
			}).Error("Failed to load statikFS, admin UI might not work :(")
		}
		mux.Handle("/js/*", http.FileServer(statikFS))
		mux.Handle("/app.32dc9945fd902da8ed2cccdc8703129f.css", http.FileServer(statikFS))
		mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			file, err := statikFS.Open("/index.html")
			if err != nil {
				w.WriteHeader(500)
				log.WithFields(log.Fields{
					"error": err,
				}).Error("got error while opening index file")
				return
			}
			io.Copy(w, file)
			w.WriteHeader(200)
		})
	}
	return mux
}
Esempio n. 17
0
// getBoneRouter returns mux for admin interface
func getBoneRouter(d DBClient) *bone.Mux {
	mux := bone.New()

	mux.Get("/records", http.HandlerFunc(d.AllRecordsHandler))
	mux.Delete("/records", http.HandlerFunc(d.DeleteAllRecordsHandler))
	mux.Post("/records", http.HandlerFunc(d.ImportRecordsHandler))

	mux.Get("/state", http.HandlerFunc(d.CurrentStateHandler))
	mux.Post("/state", http.HandlerFunc(d.stateHandler))

	return mux
}
Esempio n. 18
0
func NewHostBasedDispatcher(
	cfg *config.Configuration,
	log *logging.Logger,
	prx *proxy.ProxyHandler,
) (Dispatcher, error) {
	disp := new(hostBasedDispatcher)
	disp.cfg = cfg
	disp.log = log
	disp.prx = prx
	disp.mux = bone.New()
	disp.handlers = make(map[string]handlerPair)

	return disp, nil
}
Esempio n. 19
0
func main() {
	mux := bone.New()

	mux.NotFoundFunc(func(rw http.ResponseWriter, req *http.Request) {
		rw.WriteHeader(http.StatusTeapot)
	})

	mux.GetFunc("/", defaultHandler)
	mux.GetFunc("/reg/#var^[a-z]$/#var2^[0-9]$", ShowVar)
	mux.GetFunc("/test", defaultHandler)
	mux.Get("/file/", http.StripPrefix("/file/", http.FileServer(http.Dir("assets"))))

	http.ListenAndServe(":8080", mux)
}
Esempio n. 20
0
func getRouter(h HandlerHTTPClient) *bone.Mux {
	mux := bone.New()
	mux.Post("/stubo/api/put/stub", http.HandlerFunc(h.putStubHandler))
	mux.Post("/stubo/api/get/response", http.HandlerFunc(h.getStubResponseHandler))
	mux.Get("/stubo/api/get/stublist", http.HandlerFunc(h.stublistHandler))
	mux.Get("/stubo/api/delete/stubs", http.HandlerFunc(h.deleteStubsHandler))
	mux.Get("/stubo/api/put/delay_policy", http.HandlerFunc(h.putDelayPolicyHandler))
	mux.Get("/stubo/api/get/delay_policy", http.HandlerFunc(h.getDelayPolicyHandler))
	mux.Get("/stubo/api/delete/delay_policy", http.HandlerFunc(h.deleteDelayPolicyHandler))
	mux.Get("/stubo/api/begin/session", http.HandlerFunc(h.beginSessionHandler))
	mux.Get("/stubo/api/end/sessions", http.HandlerFunc(h.endSessionsHandler))
	mux.Get("/stubo/api/get/scenarios", http.HandlerFunc(h.getScenariosHandler))
	return mux
}
Esempio n. 21
0
func NewPathBasedDispatcher(
	cfg *config.Configuration,
	log *logging.Logger,
	prx *proxy.ProxyHandler,
) (*pathBasedDispatcher, error) {
	dispatcher := new(pathBasedDispatcher)
	dispatcher.cfg = cfg
	dispatcher.mux = bone.New()
	dispatcher.log = log
	dispatcher.prx = prx
	dispatcher.behaviours = make([]DispatcherBehaviour, 0, 8)

	return dispatcher, nil
}
Esempio n. 22
0
func main() {
	flagParse()

	mux := bone.New()
	mux.NotFound(func(w http.ResponseWriter, req *http.Request) {
		w.Write([]byte("knick-knack paddywhack give a dog a bone, this old man is no longer home"))
	})

	go databaseDumper(workers)

	mux.Get("/database/:name", http.HandlerFunc(dumpHandler))

	log.Printf("Listening on %s\n", host)
	log.Fatal(http.ListenAndServe(host, mux))
}
Esempio n. 23
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	db := storage.NewRedis()

	router := bone.New()
	router.Post("/", http.HandlerFunc(handlers.CreateKey(db)))
	router.Get("/:key", http.HandlerFunc(handlers.RedirectKey(db)))
	router.Get("/get/:key", http.HandlerFunc(handlers.GetKey(db)))

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("Service started on port %s", port)
	http.ListenAndServe(":"+port, router)
}
Esempio n. 24
0
func main() {
	if err := db.UseProd(); err != nil {
		panic(err)
	}
	db.LogMode(true)

	if err := setConfig(); err != nil {
		panic(err)
	}

	mux := bone.New()
	mux.GetFunc("/authorize", Auth)
	mux.GetFunc("/auth_callback", Callback)

	log.Printf("Start HTTP Server with port %d", config.Port)
	http.ListenAndServe(fmt.Sprintf(":%d", config.Port), hlog.Wrap(mux.ServeHTTP))
}
Esempio n. 25
0
func main() {
	// New mux instance
	mux := bone.New()
	// Custom 404
	mux.NotFound(Handler404)
	// Handle with any http method, Handle takes http.Handler as argument.
	mux.Handle("/index", http.HandlerFunc(homeHandler))
	mux.Handle("/index/:var/info/:test", http.HandlerFunc(varHandler))
	// Get, Post etc... takes http.HandlerFunc as argument.
	mux.Post("/home", http.HandlerFunc(homeHandler))
	mux.Get("/home/:var", http.HandlerFunc(varHandler))

	mux.Get("/:any", http.HandlerFunc(homeHandler))

	// Start Listening
	log.Fatal(http.ListenAndServe(":8080", mux))
}
Esempio n. 26
0
func main() {
	c := xhandler.Chain{}
	c.Use(recoverMiddleware)
	c.Use(normalLoggingMiddleware)
	c.Use(log15LoggingMiddleware)
	c.Use(logrusLoggingMiddleware)

	simpleHandler := xhandler.HandlerFuncC(simple)
	accountHandler := xhandler.HandlerFuncC(account)
	noteHandler := xhandler.HandlerFuncC(note)

	mux := bone.New()
	mux.Get("/account/:id", c.Handler(accountHandler))
	mux.Get("/note/:id", c.Handler(noteHandler))
	mux.Get("/simple", c.Handler(simpleHandler))
	http.ListenAndServe(":8080", mux)
}
Esempio n. 27
0
func loadBoneSingle(method, path string, handler http.Handler) http.Handler {
	router := bone.New()
	switch method {
	case "GET":
		router.Get(path, handler)
	case "POST":
		router.Post(path, handler)
	case "PUT":
		router.Put(path, handler)
	case "PATCH":
		router.Patch(path, handler)
	case "DELETE":
		router.Delete(path, handler)
	default:
		panic("Unknow HTTP method: " + method)
	}
	return router
}
Esempio n. 28
0
// bone
func loadBone(routes []route) http.Handler {
	router := bone.New()
	for _, route := range routes {
		switch route.method {
		case "GET":
			router.Get(route.path, http.HandlerFunc(httpHandlerFunc))
		case "POST":
			router.Post(route.path, http.HandlerFunc(httpHandlerFunc))
		case "PUT":
			router.Put(route.path, http.HandlerFunc(httpHandlerFunc))
		case "PATCH":
			router.Patch(route.path, http.HandlerFunc(httpHandlerFunc))
		case "DELETE":
			router.Delete(route.path, http.HandlerFunc(httpHandlerFunc))
		default:
			panic("Unknow HTTP method: " + route.method)
		}
	}
	return router
}
Esempio n. 29
0
func main() {
	port := flag.String("port", "80", "-port [your port]")
	flag.Parse()

	mux := bone.New()
	clw := claw.New(mw.Logger)
	// GET Handler
	mux.Get("/", clw.Use(handle.Handler))
	mux.Get("/profil", clw.Use(handle.ProfilHandler))
	mux.Get("/home", clw.Use(handle.HomeHandler))
	mux.Get("/find", clw.Use(handle.FindHandler))
	// POST Handler
	mux.Post("/signin", clw.Use(handle.SignIn))
	mux.Post("/logout", clw.Use(handle.LogOut))
	mux.Post("/add", clw.Use(handle.AddUser))
	mux.Post("/fish", clw.Use(handle.AddFish))
	mux.Post("/delete", clw.Use(handle.DeleteFish))
	// Ressources
	mux.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	// Start to serve
	http.ListenAndServe(":"+*port, mux)
}
Esempio n. 30
0
func main() {
	muxx := bone.New()
	clw := claw.New(mw.Logger)

	// API ROUTE
	muxx.Get("/api/:user", clw.Use(func(rw http.ResponseWriter, req *http.Request) {

	}))

	muxx.Post("/api/:user", clw.Use(func(rw http.ResponseWriter, req *http.Request) {
		m := &Mail{}
		err := json.NewDecoder(req.Body).Decode(m)
		if err != nil {
			json.NewEncoder(rw).Encode(err)
			return
		}
		fmt.Printf("Sending mail to %s ...\n", m.To)
		go m.Send()
	}))

	http.ListenAndServe(":8000", muxx)
}