예제 #1
0
파일: 03-routes.go 프로젝트: aerth/cosgo
func (c *Cosgo) route(cwd string) error {
	if c.routed {
		return errors.New("already is routed")
	}
	c.r = mux.NewRouter()
	//Redirect 404 errors home
	c.r.NotFoundHandler = http.HandlerFunc(redirecthomeHandler)

	// Home Page
	c.r.HandleFunc("/", c.homeHandler)
	c.r.HandleFunc("/pub.asc", c.pubkeyHandler)
	c.r.HandleFunc("/pub.txt", c.pubkeyHandler)

	// POST endpoint (emailHandler checks the key)
	c.r.HandleFunc("/{{key}}/send", c.emailHandler)

	//

	if c.staticDir != "" {
		s := http.StripPrefix("/static/", http.FileServer(http.Dir(c.staticDir)))
		ss := http.FileServer(http.Dir(c.staticDir))
		// Serve /static folder and favicon etc
		c.r.Methods("GET").Path("/favicon.ico").Handler(ss)
		c.r.Methods("GET").Path("/robots.txt").Handler(ss)
		c.r.Methods("GET").Path("/sitemap.xml").Handler(ss)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.css").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.js").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.png").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.jpg").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.jpeg").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.woff").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.ttf").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.txt").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.mp3").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.m3u").Handler(s)
		c.r.Methods("GET").Path("/static/{dir}/{whatever}.md").Handler(s)

	}

	// Serve Captcha IMG and WAV
	c.r.Methods("GET").Path("/captcha/{captchacode}.png").Handler(captcha.Server(StdWidth, StdHeight))
	c.r.Methods("GET").Path("/captcha/download/{captchacode}.wav").Handler(captcha.Server(StdWidth, StdHeight))
	c.r.Methods("GET").Path("/captcha/{captchacode}.wav").Handler(captcha.Server(StdWidth, StdHeight))

	//
	c.routed = true
	return nil
}
예제 #2
0
func main() {

	err := LoadConfig()
	if err != nil {
		log.Fatal("Could not load config file hidemyemail.cfg")
		return
	}

	g_conn_string = g_config.DbConnectionString

	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir(g_config.ResourcePath+"/images"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir(g_config.ResourcePath+"/css"))))
	http.HandleFunc("/add",
		func(w http.ResponseWriter, r *http.Request) {
			handleAdd(w, r)
		})
	http.HandleFunc("/get",
		func(w http.ResponseWriter, r *http.Request) {
			handleGet(w, r)
		})
	http.HandleFunc("/",
		func(w http.ResponseWriter, r *http.Request) {
			handleGetCaptcha(w, r)
		})
	log.Fatal(http.ListenAndServe(":"+g_config.Port, nil))
}
예제 #3
0
// main sets up the routes (thanks Gorilla!).
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", showIndex)
	r.HandleFunc("/about", showAbout)
	r.HandleFunc("/archives", showArchives)
	r.PathPrefix("/static").
		Handler(http.StripPrefix("/static",
			http.FileServer(http.Dir(staticPath))))

	// Password protect data refreshing
	authenticator := auth.NewBasicAuthenticator(
		"Refresh data", auth.HtpasswdFileProvider(*htpasswd))
	r.HandleFunc("/refresh", auth.JustCheck(authenticator, showRefresh))

	// These must be last. The first shows blog posts, the second adds comments.
	r.HandleFunc("/{postname}", showPost).Methods("GET")
	r.HandleFunc("/{postname}", addComment).Methods("POST")

	// Captcha!
	http.Handle("/captcha/",
		captcha.Server(captcha.StdWidth, captcha.StdHeight))

	// Okay, let Gorilla do its work.
	http.Handle("/", r)
	http.ListenAndServe(":8082", nil)
}
예제 #4
0
파일: main.go 프로젝트: senior7515/captcha
func main() {
	http.HandleFunc("/", showFormHandler)
	http.HandleFunc("/process", processFormHandler)
	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
	fmt.Println("Server is at localhost:8666")
	if err := http.ListenAndServe(":8666", nil); err != nil {
		log.Fatal(err)
	}
}
예제 #5
0
파일: init.go 프로젝트: netw0rm/reweb
func initHandlers() {
	var (
		serveMux     = http.NewServeMux()
		revelHandler = revel.Server.Handler
	)
	serveMux.Handle("/", revelHandler)
	// serveMux.Handle("/captcha/", http.HandlerFunc(CaptchaHanlder))
	serveMux.Handle("/captcha/", captcha.Server(CaptchaW, CaptchaH))
	revel.Server.Handler = serveMux

}
예제 #6
0
파일: web.go 프로젝트: lihex/vim-tips-web
func main() {
	routers.Initialize(m)

	http.HandleFunc("/ws", routers.WSHandler)
	http.Handle("/captcha", captcha.Server(captcha.StdWidth, captcha.StdHeight))
	http.Handle("/", m)

	fmt.Println("Server started...")

	err := http.ListenAndServe("127.0.0.1:3000", nil)
	if err != nil {
		fmt.Println(err)
	}
}
예제 #7
0
func main() {
	db := initDB()
	storage = &Database{db: db}
	go h.run()
	http.HandleFunc("/channels", channelServer)
	http.HandleFunc("/convos/", convoServer)
	http.HandleFunc("/", htmlServer)
	http.HandleFunc("/ws/", wsServer)
	http.HandleFunc("/static/", staticServer)
	http.HandleFunc("/captcha", captchaServer)
	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
	err := http.ListenAndServe(":18080", nil)
	if err != nil {
		fmt.Println("Unable to serve: ", err)
	}
}
예제 #8
0
파일: server.go 프로젝트: nosqldb/G
func StartServer() {
	http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))

	r := mux.NewRouter()
	for _, route := range routes {
		r.HandleFunc(route.URL, handlerFun(route))
	}

	r.PathPrefix("/static/").HandlerFunc(fileHandler)
	http.Handle("/", r)

	logger.Println("Server start on:", Config.Port)
	// http server
	// err := http.ListenAndServeTLS(fmt.Sprintf(":%d", Config.Port), "cert.pem", "key.pem", nil)
	err := http.ListenAndServe(fmt.Sprintf(":%d", Config.Port), nil)
	if err != nil {
		logger.Fatal(err)
	}
}
예제 #9
0
func main() {
	SavePid()
	// 服务静态文件
	http.Handle("/static/", http.FileServer(http.Dir(ROOT)))

	// 服务 sitemap 文件
	http.Handle("/sitemap/", http.FileServer(http.Dir(ROOT)))

	// 验证码
	http.Handle("/captcha/", captcha.Server(100, 40))

	go ServeWebSocket()

	go ServeBackGround()

	router := initRouter()
	http.Handle("/", router)
	log.Fatal(http.ListenAndServe(Config["host"], nil))
}
예제 #10
0
파일: captcha.go 프로젝트: JREAMLU/GoCMS
//首页
func (c *Captcha) Index() revel.Result {
	captcha.Server(250, 62)
	var CaptchaId string = c.Params.Get("CaptchaId")
	captcha.WriteImage(c.Response.Out, CaptchaId, 250, 62)
	return nil
}
예제 #11
0
파일: captcha.go 프로젝트: jsli/GoCMS
//首页
func (c *Captcha) Index() revel.Result {
	captcha.Server(250, 62)
	CaptchaId := captcha.NewLen(6)
	captcha.WriteImage(c.Response.Out, CaptchaId, 250, 62)
	return nil
}
예제 #12
0
파일: main.go 프로젝트: MadMarx/mirror
func main() {
	// Don't care if this succeeds or not at this point.
	updateMirrorMappings(remoteConfigFlag, MappingLocalLocation)

	// Setup the primary server object.
	replacers := loadMirrorMappings(MappingLocalLocation)
	myHandler := &ProxyServer{
		BufferChan: make(chan []byte, ByteBufferPoolSize),
		GzipChan:   make(chan gzipPair, GzipStreamsPoolSize),
		Client: http.Client{
			CheckRedirect: noClientRedirect,
		},
		Captcha: &CaptchaContext{
			Generator:     captcha.Server(captcha.StdWidth, captcha.StdHeight),
			Epoch:         time.Now(),
			Key:           GenerateCaptchaKey(),
			ValidDuration: HumanCookieDuration,
		},
	}
	myHandler.SetConfigurations(replacers)

	// Setup the background mapping updater.
	go loopUpdateMirrorMappings(myHandler, remoteConfigFlag, MappingLocalLocation, MappingUpdateInterval)

	// Create a waitgroup to prevent the main thread from exiting.

	// Create the HTTP server
	httpServer := http.Server{
		Addr:           httpAddr,
		Handler:        myHandler,
		ReadTimeout:    5 * time.Second,
		WriteTimeout:   5 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	go func() {
		log.Fatal(httpServer.ListenAndServe())
	}()

	// Create the HTTPS server
	tlsConfig := &tls.Config{
		Certificates: nil,
		GetCertificate: func(ch *tls.ClientHelloInfo) (*tls.Certificate, error) {
			if cfg, _ := myHandler.GetConfiguration(ch.ServerName); cfg != nil {
				if cfg.Certificate != nil {
					return cfg.Certificate, nil
				}
			}
			return nil, fmt.Errorf("Unable to find certificate for %v", ch)
		},
		NextProtos: []string{"http/1.1"},
	}
	secureServer := http.Server{
		Addr:           tlsAddr,
		Handler:        myHandler,
		ReadTimeout:    5 * time.Second,
		WriteTimeout:   5 * time.Second,
		MaxHeaderBytes: 1 << 20,
		TLSConfig:      tlsConfig,
	}
	var secureListener net.Listener
	if secureLn, err := net.Listen("tcp", secureServer.Addr); err != nil {
		log.Fatal(err)
	} else {
		secureListener = tls.NewListener(tcpKeepAliveListener{secureLn.(*net.TCPListener)}, secureServer.TLSConfig)
	}

	log.Fatal(secureServer.Serve(secureListener))
}
예제 #13
0
package models

import (
	"github.com/dchest/captcha"
)

var CaptchaHandler = captcha.Server(captcha.StdWidth, captcha.StdHeight)
예제 #14
0
파일: cmo.go 프로젝트: vichetuc/lov3lyme
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	router := models.Router
	// static
	router.Add("GET", "/static/", http.FileServer(http.Dir(models.BASE_DIR))).Name("static")
	router.Add("GET", "/uploads/", http.FileServer(http.Dir(models.DATA_DIR))).Name("uploads")
	// auth
	router.Add("GET", "/login/", controllers.Handler(controllers.LoginForm)).Name("login")
	router.Add("POST", "/login/", controllers.Handler(controllers.Login))
	router.Add("GET", "/fblogin", controllers.Handler(controllers.FbLogin)).Name("fblogin")
	router.Add("GET", "/gllogin", controllers.Handler(controllers.GlLogin)).Name("gllogin")

	router.Add("GET", "/logout/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.Logout)).Name("logout")

	router.Add("GET", "/register/", controllers.Handler(controllers.RegisterForm)).Name("register")
	router.Add("POST", "/register/", controllers.Handler(controllers.Register))
	router.Add("GET", "/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))

	router.Add("GET", "/profile/", controllers.Handler(controllers.ProfileForm)).Name("profile")
	router.Add("POST", "/profile/", controllers.Handler(controllers.Profile))

	router.Add("GET", "/reset/", controllers.Handler(controllers.ResetPasswordForm)).Name("reset")
	router.Add("POST", "/reset/", controllers.Handler(controllers.ResetPassword))

	router.Add("GET", "/change/", controllers.Handler(controllers.ChangePasswordForm)).Name("change")
	router.Add("POST", "/change/", controllers.Handler(controllers.ChangePassword))

	router.Add("GET", "/changetoken/{uuid:[0-9a-z]+}", controllers.Handler(controllers.ChangePasswordTokenForm)).Name("change_token")
	router.Add("POST", "/changetoken/{uuid:[0-9a-z]+}", controllers.Handler(controllers.ChangePasswordToken))

	// autocomplete stuff
	router.Add("GET", "/location", controllers.Handler(controllers.Location)).Name("location")
	router.Add("GET", "/country", controllers.Handler(controllers.Country)).Name("country")
	router.Add("GET", "/search", controllers.Handler(controllers.Search)).Name("search")

	// photos
	router.Add("GET", "/upload/{id:[0-9a-z]*}", controllers.Handler(controllers.UploadForm)).Name("upload")
	router.Add("POST", "/upload/{id:[0-9a-z]*}", controllers.Handler(controllers.Upload))

	router.Add("GET", "/delete/{id:[0-9a-z]+}/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.Delete)).Name("delete")

	router.Add("GET", "/photos/{id:[0-9a-z]+}/{photo:[0-9a-z]*}", controllers.Handler(controllers.Photos)).Name("photos")
	router.Add("GET", "/photo/{id:[0-9a-z]+}/{kind:p|c}/{photo:[0-9a-z]*}", controllers.Handler(controllers.ExternalPhoto)).Name("external_photo")
	router.Add("GET", "/fake/{photo:[0-9a-z]+}/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.Fake)).Name("fake")
	router.Add("GET", "/abuse/{photo:[0-9a-z]+}/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.Abuse)).Name("abuse")
	router.Add("GET", "/avatar/{photo:[0-9a-z]+}/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.SetAvatar)).Name("avatar")
	router.Add("GET", "/top/{page:[0-9]+}", controllers.Handler(controllers.TopVoted)).Name("top")
	router.Add("GET", "/latest/{page:[0-9]+}", controllers.Handler(controllers.Latest)).Name("latest")
	router.Add("GET", "/random/{page:[0-9]+}", controllers.Handler(controllers.Random)).Name("random")
	router.Add("GET", "/empty", controllers.Handler(controllers.Empty)).Name("empty")

	// admin
	router.Add("GET", "/lov3lymin1", controllers.Handler(controllers.Admin)).Name("admin")
	router.Add("GET", "/lov3lymin2/delphoto/{id:[0-9a-z]+}", controllers.Handler(controllers.DelPhoto)).Name("del_photo")
	router.Add("GET", "/lov3lymin3/deluser/{id:[0-9a-z]+}", controllers.Handler(controllers.DelUser)).Name("del_user")

	// comments
	router.Add("GET", "/comment/{kind:p|c}/{id:[0-9a-z]+}", controllers.Handler(controllers.CommentForm)).Name("comments")
	router.Add("POST", "/comment/{kind:p|c}/{id:[0-9a-z]+}", controllers.Handler(controllers.Comment))

	// votes
	router.Add("GET", "/vote/{photo:[0-9a-z]+}/{csrf_token:[0-9a-z]+}/{contest:[0-9a-z]*}", controllers.Handler(controllers.Vote)).Name("vote")
	router.Add("GET", "/getvote/{photo:[0-9a-z]+}/{contest:[0-9a-z]*}", controllers.Handler(controllers.GetVote)).Name("get_vote")
	router.Add("POST", "/filter/", controllers.Handler(controllers.Filter)).Name("filter")
	router.Add("GET", "/getphotovotes/{id:[0-9a-z]+}", controllers.Handler(controllers.GetPhotoVotes)).Name("get_photo_votes")

	// contests
	router.Add("GET", "/contests/{id:[0-9a-z]*}", controllers.Handler(controllers.ContestForm)).Name("contest")
	router.Add("POST", "/contests/{id:[0-9a-z]*}", controllers.Handler(controllers.Contest))
	router.Add("GET", "/deletecontest/{id:[0-9a-z]+}/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.DeleteContest)).Name("delete_contest")
	router.Add("GET", "/publishcontest/{id:[0-9a-z]+}/{csrf_token:[0-9a-z]+}", controllers.Handler(controllers.PublishContest)).Name("publish_contest")

	router.Add("GET", "/registercontest/{id:[0-9a-z]+}", controllers.Handler(controllers.RegisterContestForm)).Name("register_contest")
	router.Add("POST", "/registercontest/{id:[0-9a-z]+}", controllers.Handler(controllers.RegisterContest))

	router.Add("GET", "/pendingaprovals/{id:[0-9a-z]+}", controllers.Handler(controllers.PendingApprovals)).Name("pending_approvals")
	router.Add("GET", "/conteststatus/{id:[0-9a-z]+}", controllers.Handler(controllers.ContestStatus)).Name("contest_status")
	router.Add("GET", "/approvecontest/{id:[0-9a-z]+}/{user:[0-9a-z]+}/{csrf_token:[0-9a-z]+}/{res:y|n}", controllers.Handler(controllers.ApproveContest)).Name("approve_contest")
	router.Add("GET", "/viewcontest/{id:[0-9a-z]+}/{photo:[0-9a-z]*}", controllers.Handler(controllers.ViewContest)).Name("view_contest")
	router.Add("GET", "/contestlist/{list:adm|vot|fin|pop}", controllers.Handler(controllers.ContestList)).Name("contest_list")

	// rankings
	router.Add("GET", "/rankings", controllers.Handler(controllers.Rankings)).Name("rankings")

	// messageds
	router.Add("GET", "/sendmessage/{to:[0-9a-z]+}", controllers.Handler(controllers.SendMessageForm)).Name("send_message")
	router.Add("POST", "/sendmessage/{to:[0-9a-z]+}", controllers.Handler(controllers.SendMessage))
	router.Add("GET", "/messages", controllers.Handler(controllers.Messages)).Name("messages")
	router.Add("GET", "/delmessage/{id:[0-9a-z]+}", controllers.Handler(controllers.DelMessage)).Name("delete_message")

	//google web masters
	router.Add("GET", "/google4b899b9e0462f0cd.html", http.HandlerFunc(controllers.GoogleSiteVerification)).Name("google1")
	router.Add("GET", "/robots.txt", http.HandlerFunc(controllers.Robots)).Name("robots")

	//contact
	router.Add("GET", "/contact/", controllers.Handler(controllers.ContactForm)).Name("contact")
	router.Add("POST", "/contact/", controllers.Handler(controllers.Contact))

	// static
	router.Add("GET", "/page/{p:[a-z]+}", controllers.Handler(controllers.Static)).Name("page")

	// language
	router.Add("GET", "/language/{lang:[a-z]{2}}", controllers.Handler(controllers.SetLanguage)).Name("language")

	// index
	router.Add("GET", "/", controllers.Handler(controllers.Index)).Name("index")

	log.Print("The server is listening...")
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	if err := http.ListenAndServe(os.Getenv("HOST")+":"+port, router); err != nil {
		log.Print("cmo server: ", err)
	}
}
예제 #15
0
func (self *httpFrontend) Mainloop() {
	EnsureDir(self.webroot_dir)
	if !CheckFile(self.template_dir) {
		log.Fatalf("no such template folder %s", self.template_dir)
	}
	template.changeTemplateDir(self.template_dir)

	// set up handler mux
	self.httpmux = mux.NewRouter()

	self.httpmux.NotFoundHandler = template.createNotFoundHandler(self.prefix, self.name)

	// create mod ui
	self.modui = createHttpModUI(self)

	cache_handler := self.cache.GetHandler()

	// csrf protection
	b := []byte(self.secret)
	var sec [32]byte
	copy(sec[:], b)
	// TODO: make configurable
	CSRF := csrf.Protect(sec[:], csrf.Secure(false))

	m := mux.NewRouter()
	// modui handlers
	m.Path("/mod/").HandlerFunc(self.modui.ServeModPage).Methods("GET")
	m.Path("/mod/feeds").HandlerFunc(self.modui.ServeModPage).Methods("GET")
	m.Path("/mod/keygen").HandlerFunc(self.modui.HandleKeyGen).Methods("GET")
	m.Path("/mod/login").HandlerFunc(self.modui.HandleLogin).Methods("POST")
	m.Path("/mod/del/{article_hash}").HandlerFunc(self.modui.HandleDeletePost).Methods("GET")
	m.Path("/mod/ban/{address}").HandlerFunc(self.modui.HandleBanAddress).Methods("GET")
	m.Path("/mod/unban/{address}").HandlerFunc(self.modui.HandleUnbanAddress).Methods("GET")
	m.Path("/mod/addkey/{pubkey}").HandlerFunc(self.modui.HandleAddPubkey).Methods("GET")
	m.Path("/mod/delkey/{pubkey}").HandlerFunc(self.modui.HandleDelPubkey).Methods("GET")
	m.Path("/mod/admin/{action}").HandlerFunc(self.modui.HandleAdminCommand).Methods("GET", "POST")
	self.httpmux.PathPrefix("/mod/").Handler(CSRF(m))
	m = self.httpmux
	m.Path("/").Handler(cache_handler)
	// robots.txt handler
	m.Path("/robots.txt").HandlerFunc(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		io.WriteString(w, "User-Agent: *\nDisallow: /\n")
	})).Methods("GET")

	m.Path("/thm/{f}").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	m.Path("/img/{f}").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	m.Path("/{f}.html").Handler(cache_handler).Methods("GET", "HEAD")
	m.Path("/{f}.json").Handler(cache_handler).Methods("GET", "HEAD")
	m.Path("/static/{f}").Handler(http.FileServer(http.Dir(self.static_dir)))
	m.Path("/post/{f}").HandlerFunc(self.handle_poster).Methods("POST")
	m.Path("/captcha/img").HandlerFunc(self.new_captcha).Methods("GET")
	m.Path("/captcha/{f}").Handler(captcha.Server(350, 175)).Methods("GET")
	m.Path("/captcha/new.json").HandlerFunc(self.new_captcha_json).Methods("GET")
	m.Path("/new/").HandlerFunc(self.handle_newboard).Methods("GET")
	m.Path("/api/{meth}").HandlerFunc(self.handle_api).Methods("POST", "GET")
	// live ui websocket
	m.Path("/live").HandlerFunc(self.handle_liveui).Methods("GET")
	// live ui page
	m.Path("/livechan/").HandlerFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		template.writeTemplate("live.mustache", map[string]interface{}{"prefix": self.prefix}, w)
	})).Methods("GET", "HEAD")
	var err error

	// run daemon's mod engine with our frontend
	go RunModEngine(self.daemon.mod, self.cache.RegenOnModEvent)

	// start cache
	self.cache.Start()

	// before we go further ensure all db models are loaded into template model cache
	template.loadAllModels(self.prefix, self.name, self.daemon.database)

	// poll channels
	go self.poll()

	// poll liveui
	go self.poll_liveui()

	// start webserver here
	log.Printf("frontend %s binding to %s", self.name, self.bindaddr)

	// serve it!
	err = http.ListenAndServe(self.bindaddr, self.httpmux)
	if err != nil {
		log.Fatalf("failed to bind frontend %s %s", self.name, err)
	}
}
예제 #16
0
func init() {
	/* 过滤器 */
	//全部请求防止恶意代理
	var FilterProxy = func(ctx *context.Context) {
		if controllers.IsProxy(ctx.Input.Domain()) { //防止恶意代理
			ctx.Redirect(302, "/")
		}
	}
	beego.InsertFilter("/*", beego.BeforeRouter, FilterProxy)

	//全局入口
	beego.Router("/", &controllers.IndexController{}, "get:Global")
	beego.Router("/*", &controllers.IndexController{}, "get:Global")

	//api
	beego.AddNamespace(beego.NewNamespace("/api",
		//首页模块
		beego.NSNamespace("/index",
			//获取首页内容
			beego.NSRouter("/getContent", &controllers.IndexController{}, "post:GetContent"),
		),
		//验证模块
		beego.NSNamespace("/check",
			//登陆
			beego.NSRouter("/login", &controllers.CheckController{}, "post:Login"),
			//注册
			beego.NSRouter("/register", &controllers.CheckController{}, "post:Register"),
			//注销
			beego.NSRouter("/signout", &controllers.CheckController{}, "post:Signout"),
			//根据md5 token自动登陆
			beego.NSRouter("/auth", &controllers.CheckController{}, "post:Auth"),
			//社交化平台查询是否有账号,若有自动登陆
			beego.NSRouter("/hasOauth", &controllers.CheckController{}, "post:HasOauth"),
			//第三方平台注册用户
			beego.NSRouter("/oauthRegister", &controllers.CheckController{}, "post:OauthRegister"),
		),
		//游戏模块
		beego.NSNamespace("/game",
			//获取所有游戏列表
			beego.NSRouter("/getGameList", &controllers.GameController{}, "post:GetGameList"),
			//创建游戏
			beego.NSRouter("/createGame", &controllers.GameController{}, "post:CreateGame"),
			//获取游戏基础信息
			beego.NSRouter("/getInfo", &controllers.GameController{}, "post:GetInfo"),
			//获取x游戏y分类的列表
			beego.NSRouter("/getList", &controllers.GameController{}, "post:GetList"),
			//获取x游戏文章信息
			beego.NSRouter("/getPage", &controllers.GameController{}, "post:GetPage"),
			//发帖/回帖/嵌套回复
			beego.NSRouter("/addTopic", &controllers.GameController{}, "post:AddTopic"),
			//将帖子移动到其他分类下
			beego.NSRouter("/changeCategory", &controllers.GameController{}, "post:ChangeCategory"),
			//对帖子操作 置顶/加精/删除
			beego.NSRouter("/operate", &controllers.GameController{}, "post:Operate"),
			//上传图片后处理(与七牛服务器交互)
			beego.NSRouter("/uploadHandle", &controllers.GameController{}, "post:UploadHandle"),
			//管理 基本信息保存
			beego.NSRouter("/baseSave", &controllers.GameController{}, "post:BaseSave"),
			//管理 分类管理 修改优先级
			beego.NSRouter("/changeRecommendPri", &controllers.GameController{}, "post:ChangeRecommendPri"),
			//管理 新增分类
			beego.NSRouter("/addCategory", &controllers.GameController{}, "post:AddCategory"),
			//管理 更新分类
			beego.NSRouter("/updateCategory", &controllers.GameController{}, "post:UpdateCategory"),
			//管理 删除分类
			beego.NSRouter("/deleteCategory", &controllers.GameController{}, "post:DeleteCategory"),
		),
		//用户后台模块
		beego.NSNamespace("/user",
			//获取消息列表
			beego.NSRouter("/getMessage", &controllers.UserController{}, "post:GetMessage"),
			//获取充值记录
			beego.NSRouter("/getHistory", &controllers.UserController{}, "post:GetHistory"),
			//修改密码
			beego.NSRouter("/password", &controllers.UserController{}, "post:Password"),
			//生成付款订单并返回跳转表单
			beego.NSRouter("/recharge", &controllers.UserController{}, "post:Recharge"),
			//为已有未过期、未完成订单继续付款
			beego.NSRouter("/rechargeOrder", &controllers.UserController{}, "post:RechargeOrder"),
			//修改绑定邮箱 - 发送邮件
			beego.NSRouter("/email", &controllers.UserController{}, "post:Email"),
			//获取第三方平台绑定状况列表
			beego.NSRouter("/oauthList", &controllers.UserController{}, "post:OauthList"),
			//第三方平台绑定 新增/更新
			beego.NSRouter("/oauth", &controllers.UserController{}, "post:Oauth"),
			//修改用户头像
			beego.NSRouter("/changeImage", &controllers.UserController{}, "post:ChangeImage"),
			//账号管理(需要最高权限)
			beego.NSRouter("/member", &controllers.UserController{}, "post:Member"),
			//查询有哪些职位(需要最高权限)
			beego.NSRouter("/jobs", &controllers.UserController{}, "post:Jobs"),
			//职位管理(需要最高权限)
			beego.NSRouter("/job", &controllers.UserController{}, "post:Job"),
		),
		//七牛图片处理模块
		beego.NSNamespace("/qiniu",
			//获取首页内容
			beego.NSRouter("/createUpToken", &controllers.QiniuController{}, "post:CreateUpToken"),
		),
		//标签
		beego.NSNamespace("/tag",
			//绑定标签
			beego.NSRouter("/bind", &controllers.TagController{}, "post:Bind"),
			//解绑标签
			beego.NSRouter("/unBind", &controllers.TagController{}, "post:UnBind"),
			//提示推荐标签
			beego.NSRouter("/searchTag", &controllers.TagController{}, "post:SearchTag"),
			//获取标签列表
			beego.NSRouter("/getList", &controllers.TagController{}, "post:GetList"),
			//获取前30个热门标签
			beego.NSRouter("/hot", &controllers.TagController{}, "post:Hot"),
			//相似标签
			beego.NSRouter("/same", &controllers.TagController{}, "post:Same"),
		),
		// 文档
		beego.NSNamespace("/doc",
			// 获取文档
			beego.NSRouter("/getDoc", &controllers.DocController{}, "post:GetDoc"),
			// 删除文件夹
			beego.NSRouter("/deleteFolder", &controllers.DocController{}, "post:DeleteFolder"),
			// 根据文章id查询之前节点信息
			beego.NSRouter("/parents", &controllers.DocController{}, "post:Parents"),
			// 更新文档排序
			beego.NSRouter("/exchange", &controllers.DocController{}, "post:Exchange"),
		),
		// 舆情分析
		beego.NSNamespace("/yuqing",
			// 分词管理
			beego.NSRouter("/split", &controllers.YuqingController{}, "post:Split"),
			// 分析管理
			beego.NSRouter("/analyse", &controllers.YuqingController{}, "post:Analyse"),
			// 舆情列表
			beego.NSRouter("/", &controllers.YuqingController{}, "post:Index"),
			// 载入分词词库
			beego.NSRouter("/loadSego", &controllers.YuqingController{}, "post:LoadSego"),
			// 载入分析词库
			beego.NSRouter("/loadAnaylse", &controllers.YuqingController{}, "post:LoadAnaylse"),
			// 抓取信息
			beego.NSRouter("/getRss", &controllers.YuqingController{}, "post:GetRss"),
			// 抓取信息
			beego.NSRouter("/freshResult", &controllers.YuqingController{}, "post:FreshResult"),
			// 载入、抓取等操作完成状态
			beego.NSRouter("/operateStatus", &controllers.YuqingController{}, "post:OperateStatus"),
			// 图标信息
			beego.NSRouter("/charts", &controllers.YuqingController{}, "post:Charts"),
			// 中国今天的舆情
			beego.NSRouter("/china", &yuqing.China{}, "post:Read"),
			// 舆情列表/分类
			beego.NSRouter("/:category", &controllers.YuqingController{}, "post:Index"),
		),
		// 获取登陆的用户信息
		beego.NSRouter("/currentUser", &controllers.CheckController{}, "post:CurrentUser"),
		// 刷新验证码
		beego.NSRouter("/freshCap", &controllers.CheckController{}, "post:FreshCap"),
	))

	beego.Handler("/captcha/*.png", captcha.Server(240, 80)) //获取验证码图片 240 x 80

	/*

		//手机支付页面
		beego.Router("/mobile/pay.html", &controllers.ApiController{}, "get:MobilePay")

		/* 注册登录 */
	/*
		//登陆页面、登陆处理页面
		beego.Router("/login.html", &controllers.CheckController{}, "get:Login;post:PostLogin")
		//注册页面
		beego.Router("/register.html", &controllers.CheckController{}, "get:Register")

		/* check */
	/*
		beego.AddNamespace(beego.NewNamespace("/check",
			beego.NSRouter("/findpass.html", &controllers.CheckController{}, "get:FindPass;post:FindPassPost"), //找回密码页面
			beego.NSRouter("/jump.html", &controllers.CheckController{}, "get:Jump"),                           //授权码转发页面
			beego.NSRouter("/notify.html", &controllers.CheckController{}, "get:Notify"),                       //第三方登陆回调页面
			beego.NSNamespace("/post",
				beego.NSRouter("/notify", &controllers.CheckController{}, "post:NotifyPost"),             //第三方登陆回调页面-post
				beego.NSRouter("/notifyRegister", &controllers.CheckController{}, "post:NotifyRegister"), //第三方登陆,自动注册账号-post
				beego.NSRouter("/current_user", &controllers.CheckController{}, "post:CurrentUser"),      //检测登陆状态
			),
		))

		/* 网站接口 */
	/*
		beego.Router("/user.html", &controllers.UserController{}, "get:Index") //用户首页
		beego.AddNamespace(beego.NewNamespace("/web",
			beego.NSNamespace("/admin",
				beego.NSRouter("/account_base", &controllers.UserController{}, "post:AccountBase"),                           //基本信息
				beego.NSRouter("/account_message", &controllers.UserController{}, "post:AccountMessage"),                     //消息中心
				beego.NSRouter("/account_messagepost", &controllers.UserController{}, "post:AccountMessagePost"),             //消息中心-post分页查询
				beego.NSRouter("/account_messagereadpost", &controllers.UserController{}, "post:AccountMessageReadPost"),     //消息中心-post已读请求
				beego.NSRouter("/account_messagenumberpost", &controllers.UserController{}, "post:AccountMessageNumber"),     //消息中心-post获取未读消息数量
				beego.NSRouter("/account_reward", &controllers.UserController{}, "post:AccountReward"),                       //奖励额度
				beego.NSRouter("/account_history", &controllers.UserController{}, "post:AccountHistory"),                     //充值记录
				beego.NSRouter("/account_historypost", &controllers.UserController{}, "post:AccountHistoryPost"),             //充值记录-post查询
				beego.NSRouter("/account_changepass", &controllers.UserController{}, "post:AccountChangepass"),               //修改密码
				beego.NSRouter("/account_changepasspost", &controllers.UserController{}, "post:AccountChangepassPost"),       //修改密码-post
				beego.NSRouter("/account_recharge", &controllers.UserController{}, "post:AccountRecharge"),                   //账户充值
				beego.NSRouter("/account_rechargepost", &controllers.UserController{}, "post:AccountRechargePost"),           //账户充值-post 生成新账单
				beego.NSRouter("/account_rechargeorderpost", &controllers.UserController{}, "post:AccountRechargeOrderPost"), //账户充值-post 对已有账单处理
				beego.NSRouter("/account_other", &controllers.UserController{}, "post:AccountOther"),                         //账户绑定第三方平台
				beego.NSRouter("/account_free", &controllers.UserController{}, "post:AccountFree"),                           //代金券
				beego.NSRouter("/account_email", &controllers.UserController{}, "post:AccountEmail"),                         //修改绑定邮箱
				beego.NSRouter("/account_emailpost", &controllers.UserController{}, "post:AccountEmailPost"),                 //修改绑定邮箱-post
				beego.NSRouter("/job_money", &controllers.UserController{}, "post:JobMoney"),                                 //领取工资
				beego.NSRouter("/job_promotion", &controllers.UserController{}, "post:JobPromotion"),                         //我要升职
				beego.NSRouter("/job_salary", &controllers.UserController{}, "post:JobSalary"),                               //薪资管理
				beego.NSRouter("/job_salarypost", &controllers.UserController{}, "post:JobSalaryPost"),                       //薪资管理post
				beego.NSRouter("/job_manage", &controllers.UserController{}, "post:JobManage"),                               //人员管理
				beego.NSRouter("/job_managepostlist", &controllers.UserController{}, "post:JobManagePostList"),               //人员管理获取列表post
				beego.NSRouter("/job_managepost", &controllers.UserController{}, "post:JobManagePost"),                       //人员管理post
				beego.NSRouter("/job_manage_finduser", &controllers.UserController{}, "get:JobManageFindUser"),               //搜索用户
				beego.NSRouter("/article_new", &controllers.UserController{}, "post:ArticleNew"),                             //发布新文章
				beego.NSRouter("/article_newpost", &controllers.UserController{}, "post:ArticleNewPost"),                     //新文章提交post
				beego.NSRouter("/article_mylist", &controllers.UserController{}, "post:MyArticleList"),                       //我的文章列表
				beego.NSRouter("/article_mylistpage", &controllers.UserController{}, "post:MyArticleListPage"),               //我的文章列表请求分页内容
				beego.NSRouter("/article_mylistpost", &controllers.UserController{}, "post:MyArticleListPost"),               //我的文章列表post
				beego.NSRouter("/article_get_content", &controllers.UserController{}, "post:GetArticleContent"),              //获取文章信息
				beego.NSRouter("/article_category", &controllers.UserController{}, "post:ArticleCategory"),                   //分类管理
				beego.NSRouter("/article_category_post", &controllers.UserController{}, "post:ArticleCategoryPost"),          //分类管理post操作
				beego.NSRouter("/game_category", &controllers.UserController{}, "post:GameCategory"),                         //讨论组管理
				beego.NSRouter("/game_category_post", &controllers.UserController{}, "post:GameCategoryPost"),                //讨论组修改post
				beego.NSRouter("/web_count", &controllers.UserController{}, "post:WebCount"),                                 //网站统计
				beego.NSRouter("/web_useraction", &controllers.UserController{}, "post:WebUserAction"),                       //用户行为
				beego.NSRouter("/situation_spider", &controllers.UserController{}, "post:SituationSpider"),                   //抓取地址管理
				beego.NSRouter("/situation_spider_operate", &controllers.UserController{}, "post:SituationSpiderOperate"),    //抓取地址管理 增删改查
				beego.NSRouter("/situation_text", &controllers.UserController{}, "post:SituationText"),                       //正则寻址管理
				beego.NSRouter("/situation_text_operate", &controllers.UserController{}, "post:SituationTextOperate"),        //正则寻址管理 增删改查
				beego.NSRouter("/situation_text_like", &controllers.UserController{}, "post:SituationTextSelectLike"),        //正则寻址管理 模糊匹配
				beego.NSRouter("/situation_error", &controllers.UserController{}, "post:SituationError"),                     //抓取错误
				beego.NSRouter("/situation_error_operate", &controllers.UserController{}, "post:SituationErrorOperate"),      //抓取错误 增删改查
				beego.NSRouter("/user_upload", &controllers.UserController{}, "post:UserUpload"),                             //后台用户上传文件
				beego.NSRouter("/user_clear_message", &controllers.UserController{}, "post:ClearMessage"),                    //清空消息
				beego.NSRouter("/user_bind_notify", &controllers.UserController{}, "get:BindNotify"),                         //绑定第三方平台回调页面
				beego.NSRouter("/user_add_social", &controllers.UserController{}, "post:AddSocial"),                          //新增第三方平台
				beego.NSRouter("/user_change_user_head_image", &controllers.UserController{}, "post:ChangeUserHeadImage"),    //修改用户头像
			),
			beego.NSNamespace("/api", //网站api
				beego.NSRouter("/hassession", &controllers.CheckController{}, "post:HasSession"), //验证是否有登陆
				beego.NSRouter("/register", &controllers.CheckController{}, "post:PostRegister"), //注册处理页面
				beego.NSRouter("/exist", &controllers.CheckController{}, "post:DestroySession"),  //退出登陆
				beego.NSRouter("/checklogin", &controllers.CheckController{}, "post:CheckLogin"), //验证是否登陆
				beego.NSRouter("/autologin", &controllers.CheckController{}, "post:AutoLogin"),   //自动登陆
			),
		))

		/* 文章 */
	/*
		beego.AddNamespace(beego.NewNamespace("/article",
			beego.NSRouter("/:id([0-9a-z]+).html", &controllers.ArticleController{}, "get:Article"), //文章页面
			beego.NSNamespace("/post",
				beego.NSRouter("/addViews", &controllers.ArticleController{}, "post:AddViews"), //文章新增浏览数提交页面
			),
		))

		/* 分类 */
	/*
		beego.AddNamespace(beego.NewNamespace("/category",
			beego.NSRouter("/:category([a-z]+).html", &controllers.ArticleController{}, "get:Category"),               //分类首页
			beego.NSRouter("/:category([a-z]+).html/:page([0-9]+)", &controllers.ArticleController{}, "get:Category"), //分类分页面
			beego.NSNamespace("/post",
				beego.NSRouter("/getarticles", &controllers.ArticleController{}, "post:CategoryGetArticles"), //获取分类某页的文章信息post
			),
		))

		/* 游戏 game/group */
	/*
		beego.Router("/game", &controllers.GameController{}, "get:Index;post:IndexPost") //首页/获取列表
		beego.Router("/game/*", &controllers.GameController{}, "get:Index")              //列表页
		beego.AddNamespace(beego.NewNamespace("/g",
			beego.NSRouter("/:game([a-z]+)", &controllers.GameController{}, "get:Category;post:CategoryPost"),                        //游戏各分类首页和帖子内容页
			beego.NSRouter("/:game([a-z]+)/:category([0-9a-z]+)", &controllers.GameController{}, "get:Category;post:CategoryPost"),   //游戏各分类首页和帖子内容页
			beego.NSRouter("/:game([a-z]+)/:category([0-9a-z]+)/*", &controllers.GameController{}, "get:Category;post:CategoryPost"), //游戏各分类首页和帖子内容页
			beego.NSNamespace("/post",
				     //创建游戏请求
				beego.NSRouter("/getlist", &controllers.GameController{}, "post:GetList"),           //获取列表页
				beego.NSRouter("/getdetail", &controllers.GameController{}, "post:GetDetail"),       //获取详细页
				beego.NSRouter("/addtopic", &controllers.GameController{}, "post:AddTopic"),         //发帖&回帖请求post
				beego.NSRouter("/topicoperate", &controllers.GameController{}, "post:TopicOperate"), //话题置顶之类操作post
				beego.NSRouter("/findreply", &controllers.GameController{}, "post:FindReply"),       //查询子评论post
				beego.NSRouter("/upload", &controllers.GameController{}, "post:Upload"),             //上传
				beego.NSRouter("/basesave", &controllers.GameController{}, "post:BaseSave"),         //管理-基本息保存
			),
		))

		/* API接口 */
	/*
		beego.AddNamespace(beego.NewNamespace("/api",
			beego.NSRouter("/", &controllers.ApiController{}, "post:Api;get:Api"),                              //api统一接口
			beego.NSRouter("/alipayreturn.html", &controllers.ApiController{}, "get:AlipayReturn"),             //接收用户在支付宝支付成功后跳转回的页面
			beego.NSRouter("/alipaymobilereturn.html", &controllers.ApiController{}, "get:AlipayMobileReturn"), //接收用户在手机网页版支付宝支付成功后跳转回的页面
			beego.NSRouter("/alipaynotify", &controllers.ApiController{}, "post:AlipayNotify"),                 //接收用户在支付宝支付成功后异步通知地址
		))
	*/

	/* 单个页面 */
	/*
		beego.AddNamespace(beego.NewNamespace("/page",
			beego.NSRouter("/solution.html", &controllers.PageController{}, "get:Solution"),      //解决方案
			beego.NSRouter("/api.html", &controllers.PageController{}, "get:Api"),                //开发文档
			beego.NSRouter("/code_format.html", &controllers.PageController{}, "get:CodeFormat"), //代码格式化
		))

		/* socket */
	/*
		beego.Router("/ws/socket", &controllers.SocketController{}, "get:Socket")

		/* 舆情分析 */
	/*
		beego.Router("/situation.html", &controllers.SituationController{}, "get:Index") //首页
		beego.AddNamespace(beego.NewNamespace("/situation"))

		/* 手机 */
	/*
		beego.AddNamespace(beego.NewNamespace("/mobile",
			beego.NSNamespace("/post",
				beego.NSRouter("/category", &controllers.ArticleController{}, "post:CategoryGetArticles"), //获取分类列表
			),
		))

		/* 验证码 */
	/*
		beego.Handler("/captcha/*.png", captcha.Server(240, 80)) //注册验证码服务,验证码图片的宽高为240 x 80
	*/
}
예제 #17
0
func (cs *CaptchaServer) SetupRoutes(m *mux.Router) {
	m.Path("/new").HandlerFunc(cs.NewCaptcha)
	m.Path("/img/{f}").Handler(captcha.Server(cs.w, cs.h))
	m.Path("/verify.json").HandlerFunc(cs.VerifyCaptcha)
}
예제 #18
0
파일: web.go 프로젝트: rschulman/nodeatlas
	"net/http"
	"os"
	"path"
	"strings"
	"time"
)

var (
	NodeRSS     *moverss.Channel
	NodeXMLName xml.Name
)

var (
	listener net.Listener

	captchaServer = captcha.Server(captcha.StdWidth, captcha.StdHeight)
)

var (
	InvalidBindAddress   = errors.New("invalid address to bind to")
	InvalidCAPTCHAFormat = errors.New("CAPTCHA format invalid")
	IncorrectCAPTCHA     = errors.New("CAPTCHA ID or solution is incorrect")
)

// StartServer is a simple helper function to register any handlers
// (such as the API) and start the HTTP server on the configured
// address (Conf.Web.Addr).
//
// If Conf.Web.Prefix or Conf.Web.DeproxyHeaderFields has a length
// greater than zero, it wraps its http.ServeMux with a Deproxier.
//
예제 #19
0
파일: init.go 프로젝트: netw0rm/reweb
}

func initHandlers() {
	var (
		serveMux     = http.NewServeMux()
		revelHandler = revel.Server.Handler
	)
	serveMux.Handle("/", revelHandler)
	// serveMux.Handle("/captcha/", http.HandlerFunc(CaptchaHanlder))
	serveMux.Handle("/captcha/", captcha.Server(CaptchaW, CaptchaH))
	revel.Server.Handler = serveMux

}

var CaptchaHanlder = func(w http.ResponseWriter, r *http.Request) {
	log.Println("CaptchaHandler handling...")
	captcha.Server(CaptchaW, CaptchaH).ServeHTTP(w, r)
}

// TODO turn this into revel.HeaderFilter
// should probably also have a filter for CSRF
// not sure if it can go in the same filter or not
var HeaderFilter = func(c *revel.Controller, fc []revel.Filter) {
	// Add some common security headers
	c.Response.Out.Header().Add("X-Frame-Options", "SAMEORIGIN")
	c.Response.Out.Header().Add("X-XSS-Protection", "1; mode=block")
	c.Response.Out.Header().Add("X-Content-Type-Options", "nosniff")

	fc[0](c, fc[1:]) // Execute the next filter stage.
}
예제 #20
0
func (self httpFrontend) Mainloop() {
	EnsureDir(self.webroot_dir)
	if !CheckFile(self.template_dir) {
		log.Fatalf("no such template folder %s", self.template_dir)
	}

	threads := self.regen_threads

	// check for invalid number of threads
	if threads <= 0 {
		threads = 1
	}

	// set up handler mux
	self.httpmux = mux.NewRouter()

	// create mod ui
	self.modui = createHttpModUI(self)

	// modui handlers
	self.httpmux.Path("/mod/").HandlerFunc(self.modui.ServeModPage).Methods("GET")
	self.httpmux.Path("/mod/keygen").HandlerFunc(self.modui.HandleKeyGen).Methods("GET")
	self.httpmux.Path("/mod/login").HandlerFunc(self.modui.HandleLogin).Methods("POST")
	self.httpmux.Path("/mod/del/{article_hash}").HandlerFunc(self.modui.HandleDeletePost).Methods("GET")
	self.httpmux.Path("/mod/ban/{address}").HandlerFunc(self.modui.HandleBanAddress).Methods("GET")
	self.httpmux.Path("/mod/unban/{address}").HandlerFunc(self.modui.HandleUnbanAddress).Methods("GET")
	self.httpmux.Path("/mod/addkey/{pubkey}").HandlerFunc(self.modui.HandleAddPubkey).Methods("GET")
	self.httpmux.Path("/mod/delkey/{pubkey}").HandlerFunc(self.modui.HandleDelPubkey).Methods("GET")
	self.httpmux.Path("/mod/admin/{action}").HandlerFunc(self.modui.HandleAdminCommand).Methods("GET", "POST")
	// webroot handler
	self.httpmux.Path("/").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	self.httpmux.Path("/thm/{f}").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	self.httpmux.Path("/img/{f}").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	self.httpmux.Path("/{f}.html").Handler(http.FileServer(http.Dir(self.webroot_dir)))
	self.httpmux.Path("/static/{f}").Handler(http.FileServer(http.Dir(self.static_dir)))
	// post handler
	self.httpmux.Path("/post/{f}").HandlerFunc(self.handle_poster).Methods("POST")
	// captcha handlers
	self.httpmux.Path("/captcha/img").HandlerFunc(self.new_captcha).Methods("GET")
	self.httpmux.Path("/captcha/{f}").Handler(captcha.Server(350, 175)).Methods("GET")
	self.httpmux.Path("/captcha/new.json").HandlerFunc(self.new_captcha_json).Methods("GET")
	// helper handlers
	self.httpmux.Path("/new/").HandlerFunc(self.handle_newboard).Methods("GET")
	// liveui handlers
	self.httpmux.Path("/live/").HandlerFunc(self.handle_liveui_index).Methods("GET")
	self.httpmux.Path("/live/options").HandlerFunc(self.handle_liveui_options).Methods("GET")
	self.httpmux.Path("/live/ws").HandlerFunc(self.handle_liveui).Methods("GET")

	var err error

	// poll channels
	go self.poll()
	go self.pollRegen()

	go RunModEngine(self.daemon.mod, self.regenOnModEvent)

	// start webserver here
	log.Printf("frontend %s binding to %s", self.name, self.bindaddr)

	err = http.ListenAndServe(self.bindaddr, self.httpmux)
	if err != nil {
		log.Fatalf("failed to bind frontend %s %s", self.name, err)
	}
}
예제 #21
0
// Copyright 2016 The StudyGolang Authors. All rights reserved.
// Use of self source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// http://studygolang.com
// Author: polaris	[email protected]

package controller

import (
	. "http"

	"github.com/dchest/captcha"
	"github.com/labstack/echo"
)

var captchaHandler = captcha.Server(100, 40)

// 验证码
type CaptchaController struct{}

func (self CaptchaController) RegisterRoute(g *echo.Group) {
	g.Get("/captcha/*", self.Server)
}

func (CaptchaController) Server(ctx echo.Context) error {
	captchaHandler.ServeHTTP(ResponseWriter(ctx), Request(ctx))
	return nil
}