Example #1
0
func (cfg *Config) Handler(h http.Handler) http.Handler {
	cfg.mustInit()

	// TODO: nonce?
	csp := "default-src 'self' https://www.google-analytics.com; frame-ancestors 'none'; img-src 'self' https://www.google-analytics.com data:; form-action 'self'; plugin-types;"
	if reportURI.Value() != "" {
		csp += fmt.Sprintf(" report-uri %s;", reportURI.Value())
	}

	var h2 http.Handler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		cRequestsHandled.Inc()

		miscctx.SetResponseWriter(rw, req)
		context.Set(req, &ServerKey, cfg.Server)

		hdr := rw.Header()
		hdr.Set("X-Frame-Options", "DENY")
		hdr.Set("X-Content-Type-Options", "nosniff")
		hdr.Set("X-UA-Compatible", "ie=edge")
		hdr.Set("Content-Security-Policy", csp)
		if origin.IsSSL(req) {
			hdr.Set("Strict-Transport-Security", "max-age=15552000")
		}

		if !opts.DevMode && !cfg.NoForceSSL && !origin.IsSSL(req) {
			cfg.redirectHTTPS(rw, req)
			return
		}

		if cfg.StripWWW && strings.HasPrefix(req.Host, "www.") {
			cfg.redirectStripWWW(rw, req)
			return
		}

		h.ServeHTTP(rw, req)
	})

	if cfg.SessionConfig != nil {
		h2 = cfg.SessionConfig.InitHandler(h2)
	}

	if cfg.CAPTCHA == nil {
		cfg.CAPTCHA = &captcha.Config{
			DisallowHandlerNew: true,
			Leeway:             1,
		}

		if captchaFontPathFlag.Value() != "" {
			cfg.CAPTCHA.SetFontPath(captchaFontPathFlag.Value())
		}
	}

	mux := http.NewServeMux()
	mux.Handle("/", h2)
	mux.Handle("/.captcha/", cfg.CAPTCHA.Handler("/.captcha/"))
	mux.Handle("/.csp-report", cspreport.Handler)
	mux.Handle("/.service-nexus/", servicenexus.Handler(h2))
	return context.ClearHandler(timingHandler(errorhandler.Handler(methodOverride(mux))))
}
Example #2
0
func newRouter(o Options, h *handler) *router {
	mux := mux.NewRouter()
	mux.Handle(employeeURL, responseHandler(h.ListEmployees)).Methods("GET")
	mux.Handle(employeeURL, responseHandler(h.AddEmployee)).Methods("PUT")
	mux.Handle(employeeURL, responseHandler(h.DeleteEmployee)).Methods("DELETE")

	return &router{o, mux}
}
Example #3
0
func newRouter(o Options, h *handler) *router {
	mux := mux.NewRouter()
	mux.Handle(catalogUrlPattern, reponseHandler(h.catalog)).Methods("GET")
	mux.Handle(provisioningUrlPattern, reponseHandler(h.provision)).Methods("PUT")
	mux.Handle(provisioningUrlPattern, reponseHandler(h.deprovision)).Methods("DELETE")
	mux.Handle(bindingUrlPattern, reponseHandler(h.bind)).Methods("PUT")
	mux.Handle(bindingUrlPattern, reponseHandler(h.unbind)).Methods("DELETE")
	return &router{o, mux}
}
Example #4
0
func main() {

	var home RefHandler
	var search SearchHandler
	var login LoginHandler
	var logout LogoutHandler
	var admin AdminViewHandler
	var searchAdmin SearchAdminHandler
	var edit EditHandler
	var delete DeleteHandler
	var new NewHandler

	port := ":8080"
	log.Println("Starting Web Server 127.0.0.1" + port)
	go Exit()

	webbrowser.Open("http://localhost" + port)

	mux := mux.NewRouter()

	mux.Handle("/", home).Name("home")
	mux.Handle("/search", search)
	mux.Handle("/login", login).Methods("POST")
	mux.Handle("/logout", logout)
	mux.Handle("/admin", admin)
	mux.Handle("/admin/search", searchAdmin)
	mux.Handle("/admin/new", new)
	mux.Handle("/admin/edit/{id}", edit)
	mux.Handle("/admin/delete/{id}", delete)

	err := http.ListenAndServe(port, mux)
	check(err)
}
Example #5
0
func main() {
	log.Level = logrus.DebugLevel
	log.Print("Starting Reclus Issue Tracker...")

	if err := loadConfig(conf); err != nil {
		log.Fatal(err)
	}

	db, err := NewDatabase(conf)

	if err != nil {
		log.Fatal(err)
	}

	defer db.Close()

	if err = setupAuth(db); err != nil {
		log.Fatal(err)
	}

	mux := mux.NewRouter()

	mux.PathPrefix("/auth").Handler(authManager.NewRouter())
	mux.Handle("/", authProtect(loggedIn))

	http.ListenAndServe(":9090", mux)
}
Example #6
0
File: web.go Project: yubobo/minio
// HTTPHandler - http wrapper handler
func HTTPHandler() http.Handler {
	mux := mux.NewRouter()
	var api = webAPI{}

	if err := api.conf.SetupConfig(); err != nil {
		log.Fatal(iodine.New(err, nil))
	}

	api.webPath = filepath.Join(api.conf.GetConfigPath(), defaultWeb)
	mux.Handle("/{polygon:.*}", http.FileServer(http.Dir(api.webPath))).Methods("GET")
	mux.HandleFunc("/access", api.accessHandler).Methods("POST")
	return mux
}
Example #7
0
func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello from " + r.RemoteAddr + "\n"))
	})

	mux := mux.NewRouter()
	mux.Handle("/", handler)

	n := negroni.Classic()
	n.Use(negroni.HandlerFunc(xff.XFF))
	n.UseHandler(mux)
	n.Run(":3000")
}
Example #8
0
func (s *App) Start() error {
	log.Println("HTTP: Starting Demo Http Server")

	r := mux.NewRouter()

	r.HandleFunc("/foo", Handle).Methods("GET")

	mux := http.NewServeMux()
	mux.Handle("/", r)
	//http.Handle("/", r)

	return s.S.Start(mux)
}
Example #9
0
func init() {
	ahipbot.RegisterWebHandler(func(bot *ahipbot.Bot, plugins []ahipbot.Plugin) ahipbot.WebHandler {
		var conf struct {
			Webapp WebappConfig
		}
		bot.LoadConfig(&conf)

		webapp := &Webapp{
			bot:    bot,
			config: &conf.Webapp,
			store:  sessions.NewCookieStore([]byte(conf.Webapp.SessionAuthKey), []byte(conf.Webapp.SessionEncryptKey)),
		}

		configureWebapp(&conf.Webapp)

		web = webapp

		rt := mux.NewRouter()
		rt.HandleFunc("/", handleRoot)

		for _, plugin := range plugins {
			webPlugin, ok := plugin.(WebPlugin)
			if !ok {
				continue
			}
			webPlugin.WebPluginSetup(rt)
		}

		mux := http.NewServeMux()
		mux.Handle("/static/", http.StripPrefix("/static", http.FileServer(rice.MustFindBox("static").HTTPBox())))
		mux.Handle("/", rt)

		webapp.handler = negroni.Classic()
		webapp.handler.UseHandler(context.ClearHandler(NewOAuthMiddleware(mux)))
		return webapp
	})
}
Example #10
0
// RunTLS starts the web application and serves HTTPS requests for s.
func (s *Server) RunTLS(addr string, config *tls.Config) error {
	s.initServer()
	mux := http.NewServeMux()
	mux.Handle("/", s)

	s.Logger.Printf("serving %s\n", addr)

	l, err := tls.Listen("tcp", addr, config)
	if err != nil {
		log.Fatal("Listen:", err)
		return err
	}

	s.l = l
	return http.Serve(s.l, mux)
}
Example #11
0
func setupJSONService(c *client.Conn) {
	tcpConn, err := net.Listen("tcp", fmt.Sprintf("%v:%v", *listenIp, *jsonPort))
	if err != nil {
		panic(err)
	}
	router := mux.NewRouter()
	router.Methods("POST").Path(fmt.Sprintf("/%v/{user_id}", common.Recommend)).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		getRecommendations(w, r, c)
	})
	router.Methods("GET").Path(fmt.Sprintf("/%v/{user_id}", common.Views)).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		getViews(w, r, c)
	})
	router.Methods("GET").Path(fmt.Sprintf("/%v/{user_id}", common.Likes)).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		getLikes(w, r, c)
	})
	router.Methods("GET").Path(fmt.Sprintf("/%v", common.Actives)).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		getActives(w, r, c)
	})
	mux := http.NewServeMux()
	mux.Handle("/", router)
	(&http.Server{Handler: mux}).Serve(tcpConn)
}
Example #12
0
File: n.go Project: esiqveland/den
func main() {
	// verify tesseract is available...
	goss, err := gosseract.NewClient()
	if err != nil {
		log.Fatalln(err.Error())
	}

	session, err := r.Connect(r.ConnectOpts{
		Address:  "localhost:28015",
		Database: "test",
	})
	if err != nil {
		log.Fatalln(err.Error())
	}

	mux := mux.NewRouter()
	mux.Handle("/post/new", createImageHandler(goss, NewPostingStore(session))).
		Methods("POST")

	mw := negroni.Classic()
	mw.UseHandler(mux)
	mw.Run(":1234")
}
Example #13
0
func main() {

	// Store
	var store = (configstore.Store)(file.NewFileStore("/var/tmp/data", file.DefaultDateFormat))

	// HTTP endpoints
	mux := mux.NewRouter()
	mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	mux.HandleFunc("/api", apiDoc)
	mux.Handle("/", http.RedirectHandler("/dashboard", 302))
	mux.HandleFunc("/dashboard", func(w http.ResponseWriter, req *http.Request) {
		dashboard(store, w, req)
	})
	mux.HandleFunc("/hosts", func(w http.ResponseWriter, req *http.Request) {
		listHosts(store, w, req)
	})
	mux.HandleFunc("/hosts/{hostname}", func(w http.ResponseWriter, req *http.Request) {
		listDates(store, w, req)
	})
	mux.HandleFunc("/hosts/{hostname}/dates/{date}", func(w http.ResponseWriter, req *http.Request) {
		hostBackup(store, w, req)
	})
	mux.HandleFunc("/hosts/{hostname}/on/{date}", func(w http.ResponseWriter, req *http.Request) {
		showBackupDate(store, w, req)
	})
	mux.HandleFunc("/hosts/{hostname}/diff/{date1}/{date2}", func(w http.ResponseWriter, req *http.Request) {
		diffBackup(store, w, req)
	})

	// Start HTTP server
	s := &http.Server{
		Addr:    ":8080",
		Handler: mux,
	}
	s.ListenAndServe()

}
//  Tiger Tonic
func startTigerTonic() {
	mux := tigertonic.NewTrieServeMux()
	mux.Handle("GET", "/hello", http.HandlerFunc(helloHandler))
	http.ListenAndServe(":"+strconv.Itoa(port), mux)
}
Example #15
0
func (self *Node) startJson() {
	var nodeAddr *net.TCPAddr
	var err error
	if nodeAddr, err = net.ResolveTCPAddr("tcp", self.node.GetListenAddr()); err != nil {
		return
	}
	rpcServer := rpc.NewServer()
	jsonApi := (*JSONApi)(self)
	web.SetApi(reflect.TypeOf(jsonApi))
	rpcServer.RegisterName("DHash", jsonApi)
	jsonServer := jsonRpcServer{server: rpcServer}
	router := mux.NewRouter()
	router.Methods("POST").Path("/rpc/{method}").MatcherFunc(wantsJSON).Handler(jsonServer)
	web.Route(func(ws *websocket.Conn) {
		if websocket.Message.Send(ws, self.jsonDescription()) == nil {
			go func() {
				for {
					time.Sleep(updateInterval)
					if websocket.Message.Send(ws, self.jsonDescription()) != nil {
						break
					}
				}
			}()
			self.AddCommListener(func(comm Comm) bool {
				b, err := json.Marshal(socketMessage{
					Type: "Comm",
					Data: map[string]interface{}{
						"source":      comm.Source,
						"destination": comm.Destination,
						"key":         comm.Key,
						"sub_key":     comm.SubKey,
						"type":        comm.Type,
					},
				})
				if err != nil {
					panic(err)
				}
				return websocket.Message.Send(ws, string(b)) == nil
			})
			self.AddChangeListener(func(ring *common.Ring) bool {
				b, err := json.Marshal(socketMessage{
					Type: "RingChange",
					Data: map[string]interface{}{
						"description": self.Description(),
						"routes":      self.node.Nodes(),
					},
				})
				if err != nil {
					panic(err)
				}
				return websocket.Message.Send(ws, string(b)) == nil
			})
			self.AddSyncListener(func(source, dest common.Remote, pulled, pushed int) bool {
				b, err := json.Marshal(socketMessage{
					Type: "Sync",
					Data: map[string]interface{}{
						"source":      source,
						"destination": dest,
						"pulled":      pulled,
						"pushed":      pushed,
					},
				})
				if err != nil {
					panic(err)
				}
				return websocket.Message.Send(ws, string(b)) == nil
			})
			self.AddCleanListener(func(source, dest common.Remote, cleaned, pushed int) bool {
				b, err := json.Marshal(socketMessage{
					Type: "Clean",
					Data: map[string]interface{}{
						"source":      source,
						"destination": dest,
						"cleaned":     cleaned,
						"pushed":      pushed,
					},
				})
				if err != nil {
					panic(err)
				}
				return websocket.Message.Send(ws, string(b)) == nil
			})
			var mess string
			for {
				if err = websocket.Message.Receive(ws, &mess); err != nil {
					break
				}
			}
		}
	}, router)
	mux := http.NewServeMux()
	mux.Handle("/", router)
	listener, err := net.Listen("tcp", fmt.Sprintf("%v:%v", nodeAddr.IP, nodeAddr.Port+1))
	if err != nil {
		panic(err)
	}
	go (&http.Server{
		Handler: mux,
	}).Serve(listener)
}
Example #16
0
func newRouter(o Options, h *handler) *router {
	mux := mux.NewRouter()
	mux.Handle(catalogUrlPattern, responseHandler(h.catalog)).Methods("GET")
	mux.Handle(provisioningUrlPattern, responseHandler(h.provision)).Methods("PUT")
	mux.Handle(provisioningUrlPattern, responseHandler(h.deprovision)).Methods("DELETE")
	mux.Handle(bindingUrlPattern, responseHandler(h.bind)).Methods("PUT")
	mux.Handle(bindingUrlPattern, responseHandler(h.unbind)).Methods("DELETE")
	mux.Handle(pingUrlPattern, responseHandler(h.ping)).Methods("POST")
	mux.Handle(imageUrlPattern, responseHandler(h.addimage)).Methods("PUT")
	mux.Handle(imageUrlPattern, responseHandler(h.getimage)).Methods("GET")
	mux.Handle(imageUrlPattern, responseHandler(h.delimage)).Methods("DELETE")
	mux.Handle(certUrlPattern, responseHandler(h.addcerts)).Methods("PUT")
	mux.Handle(certUrlPattern, responseHandler(h.getcerts)).Methods("GET")
	mux.Handle(certUrlPattern, responseHandler(h.delcerts)).Methods("DELETE")
	mux.Handle(imageAllUrlPattern, responseHandler(h.getimage)).Methods("GET")
	mux.Handle(certAllUrlPattern, responseHandler(h.getcerts)).Methods("GET")
	return &router{o, mux}
}