// starts http handlers for HTML content based on the given configuration file // optional parameters: default.contentDirectory (location of html content to be served at https://example.com/ or https://example.com/html/index.html func StartHtmlHandler() { if contentDir, _ := configFile.GetString("default", "contentDirectory"); contentDir != "" { logger.Printf("StartHtmlHandler(): serving HTML content from [%v]", contentDir) http.Handle("/html/", http.StripPrefix("/html/", http.FileServer(http.Dir(contentDir)))) http.Handle("/", http.RedirectHandler("/html/", http.StatusTemporaryRedirect)) } }
func signupPost(w http.ResponseWriter, r *http.Request) { responseType, client, err := params(r) if err != nil { err.WriteTo(w) return } email, password := r.FormValue("email"), r.FormValue("password") emailRegexp := regexp.MustCompile(`^[a-z0-9._%\-+]+@[a-z0-9.\-]+\.[a-z]+$`) msgs := make([]string, 0, 5) if !emailRegexp.MatchString(email) { msgs = append(msgs, "Invalid email address") } if len(password) < 6 { msgs = append(msgs, "Password is too short") } // Also check if email already exists user := model.NewUser(email) context := appengine.NewContext(r) countExists, e := datastore.NewQuery("User").Filter("EmailHash =", user.EmailHash).Count(context) if e != nil { context.Errorf("%v", e) http.Error(w, e.String(), http.StatusInternalServerError) return } if countExists > 0 { msgs = append(msgs, "Email already exists") } if msgsLen := len(msgs); msgsLen > 0 { http.RedirectHandler("/oauth2/signup?response_type="+url.QueryEscape(responseType)+"&client_id="+ url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape(strings.Join(msgs, "|")), 303).ServeHTTP(w, r) } else { userKey, err := datastore.Put(context, datastore.NewIncompleteKey(context, "User", nil), user) if err != nil { context.Errorf("Error saving: %v", err) w.Write([]byte("Error saving: " + err.String())) return } auth := model.NewPasswordAuth(userKey, password) if _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Authentication", nil), auth); err != nil { context.Errorf("Error saving: %v", err) w.Write([]byte("Error saving: " + err.String())) return } key := newCodeKey(userKey.StringID(), client.Id, context) http.RedirectHandler(client.redirectUrl(key), 303).ServeHTTP(w, r) } }
func loginPost(w http.ResponseWriter, r *http.Request) { responseType, client, err := params(r) if err != nil { err.WriteTo(w) return } email, password := r.FormValue("email"), r.FormValue("password") emailHash := model.UserEmail(email) context := appengine.NewContext(r) query := datastore.NewQuery("User").Filter("EmailHash =", emailHash) found, hasEntries := false, false var foundKey *datastore.Key for row := query.KeysOnly().Run(context); ; { key, e := row.Next(nil) if e == datastore.Done { break } query := datastore.NewQuery("Authentication").Filter("Type =", "password").Filter("User ="******"/oauth2/auth?response_type="+url.QueryEscape(responseType)+"&client_id="+ url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape("Incorrect Email or Password"), 303).ServeHTTP(w, r) } } if !hasEntries { http.RedirectHandler("/oauth2/auth?response_type="+url.QueryEscape(responseType)+"&client_id="+ url.QueryEscape(client.Id)+"&msgs="+url.QueryEscape("Incorrect Email or Password"), 303).ServeHTTP(w, r) } }
func Serve(listener net.Listener) { prefix := "/d/" + ClusterName evPrefix = "/events" + prefix http.Handle("/", http.RedirectHandler("/view/d/"+ClusterName+"/", 307)) http.HandleFunc("/view/", viewHtml) http.Handle("/main.js", stringHandler{"application/javascript", main_js}) http.Handle("/main.css", stringHandler{"text/css", main_css}) http.HandleFunc(evPrefix+"/", evServer) http.Serve(listener, nil) }
func main() { loader := model.FileLoader() actions := map[string]handler.Action{ "view": handler.ViewAction(loader, tmplFilename("view"), "edit"), "edit": handler.EditAction(loader, tmplFilename("edit")), "save": handler.SaveAction(loader, "view"), } handler.CreateAndRegisterHandler(actions) http.Handle("/", http.RedirectHandler("/view/FrontPage", http.StatusFound)) fmt.Println("Listening on :8080") http.ListenAndServe(":8080", nil) }
// Handle registers the handler for the given pattern. func (mux *ServeMux) Handle(pattern string, handler http.Handler) { if pattern == "" { panic("http: invalid pattern " + pattern) } mux.M[pattern] = handler // Helpful behavior: // If pattern is /tree/, insert permanent redirect for /tree. n := len(pattern) if n > 0 && pattern[n-1] == '/' { mux.M[pattern[0:n-1]] = http.RedirectHandler(pattern, http.StatusMovedPermanently) } }
func main() { flag.Parse() readTemplates() if *root == "" { var err os.Error *root, err = os.Getwd() if err != nil { log.Exitf("Failed to getwd: %v", err) } } mux := http.DefaultServeMux mux.Handle("/favicon.ico", http.FileServer(path.Join(*root, "static"), "/")) mux.Handle("/robots.txt", http.FileServer(path.Join(*root, "static"), "/")) mux.Handle("/static/", http.FileServer(path.Join(*root, "static"), "/static/")) testCgi := &CgiHandler{ExecutablePath: path.Join(*root, "test.cgi"), Root: "/test.cgi", } mux.Handle("/test.cgi", testCgi) mux.Handle("/test.cgi/foo", testCgi) mux.Handle("/code", http.RedirectHandler("/code/", http.StatusFound)) if *gitwebScript != "" { env := os.Environ() env = append(env, "GITWEB_CONFIG="+path.Join(*root, "gitweb-camli.conf")) env = append(env, "CAMWEB_ROOT="+path.Join(*root)) mux.Handle("/code/", &gitwebHandler{ Cgi: &CgiHandler{ ExecutablePath: *gitwebScript, Root: "/code/", Environ: env, }, Static: http.FileServer(*gitwebFiles, "/code/"), }) } mux.HandleFunc("/", mainHandler) var handler http.Handler = &noWwwHandler{Handler: mux} if *logDir != "" || *logStdout { handler = NewLoggingHandler(handler, *logDir, *logStdout) } if err := http.ListenAndServe(*httpAddr, handler); err != nil { log.Exitf("ListenAndServe %s: %v", *httpAddr, err) } }
func init() { http.Handle("/", http.RedirectHandler("http://surma.github.com/trendinghubs", http.StatusMovedPermanently)) http.HandleFunc("/feed", generateFeed) }
func main() { flag.Parse() readTemplates() if *root == "" { var err os.Error *root, err = os.Getwd() if err != nil { log.Fatalf("Failed to getwd: %v", err) } } fixupGitwebFiles() latestGits := filepath.Join(*root, "latestgits") os.Mkdir(latestGits, 0700) if *gerritHost != "" { go rsyncFromGerrit(latestGits) } mux := http.DefaultServeMux mux.Handle("/favicon.ico", http.FileServer(http.Dir(filepath.Join(*root, "static")))) mux.Handle("/robots.txt", http.FileServer(http.Dir(filepath.Join(*root, "static")))) mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(filepath.Join(*root, "static"))))) mux.Handle("/talks/", http.StripPrefix("/talks/", http.FileServer(http.Dir(filepath.Join(*root, "talks"))))) gerritUrl, _ := url.Parse("http://gerrit-proxy:8000/") var gerritHandler http.Handler = http.NewSingleHostReverseProxy(gerritUrl) if *httpsAddr != "" { proxyHandler := gerritHandler gerritHandler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if req.TLS != nil { proxyHandler.ServeHTTP(rw, req) return } http.Redirect(rw, req, "https://camlistore.org"+req.URL.RawPath, http.StatusFound) }) } mux.Handle("/r/", gerritHandler) testCgi := &cgi.Handler{Path: filepath.Join(*root, "test.cgi"), Root: "/test.cgi", } mux.Handle("/test.cgi", testCgi) mux.Handle("/test.cgi/foo", testCgi) mux.Handle("/code", http.RedirectHandler("/code/", http.StatusFound)) if *gitwebScript != "" { env := os.Environ() env = append(env, "GITWEB_CONFIG="+filepath.Join(*root, "gitweb-camli.conf")) env = append(env, "CAMWEB_ROOT="+filepath.Join(*root)) env = append(env, "CAMWEB_GITDIR="+latestGits) mux.Handle("/code/", &fixUpGitwebUrls{&gitwebHandler{ Cgi: &cgi.Handler{ Path: *gitwebScript, Root: "/code/", Env: env, }, Static: http.StripPrefix("/code/", http.FileServer(http.Dir(*gitwebFiles))), }}) } mux.HandleFunc("/", mainHandler) var handler http.Handler = &noWwwHandler{Handler: mux} if *logDir != "" || *logStdout { handler = NewLoggingHandler(handler, *logDir, *logStdout) } errch := make(chan os.Error) httpServer := &http.Server{ Addr: *httpAddr, Handler: handler, ReadTimeout: connTimeoutNanos, WriteTimeout: connTimeoutNanos, } go func() { errch <- httpServer.ListenAndServe() }() if *httpsAddr != "" { log.Printf("Starting TLS server on %s", *httpsAddr) httpsServer := new(http.Server) *httpsServer = *httpServer httpsServer.Addr = *httpsAddr go func() { errch <- httpsServer.ListenAndServeTLS(*tlsCertFile, *tlsKeyFile) }() } log.Fatalf("Serve error: %v", <-errch) }
// Match matches this route against the request. // // It sets variables from the matched route in the context, if any. func (r *Route) Match(req *http.Request) (*RouteMatch, bool) { var hostMatches, pathMatches []string if r.hostTemplate != nil { hostMatches = r.hostTemplate.Regexp.FindStringSubmatch(req.URL.Host) if hostMatches == nil { return nil, false } } var redirectURL string if r.pathTemplate != nil { // TODO Match the path unescaped? /* if path, ok := url.URLUnescape(r.URL.Path); ok { // URLUnescape converts '+' into ' ' (space). Revert this. path = strings.Replace(path, " ", "+", -1) } else { path = r.URL.Path } */ pathMatches = r.pathTemplate.Regexp.FindStringSubmatch(req.URL.Path) if pathMatches == nil { return nil, false } else if r.redirectSlash { // Check if we should redirect. p1 := strings.HasSuffix(req.URL.Path, "/") p2 := strings.HasSuffix(r.pathTemplate.Template, "/") if p1 != p2 { ru, _ := url.Parse(req.URL.String()) if p1 { ru.Path = ru.Path[:len(ru.Path)-1] } else { ru.Path = ru.Path + "/" } redirectURL = ru.String() } } } var match *RouteMatch if r.matchers != nil { for _, matcher := range r.matchers { if rv, ok := (*matcher).Match(req); !ok { return nil, false } else if rv != nil { match = rv break } } } // We have a match. vars := make(RouteVars) if hostMatches != nil { for k, v := range r.hostTemplate.VarsN { vars[v] = hostMatches[k+1] } } if pathMatches != nil { for k, v := range r.pathTemplate.VarsN { vars[v] = pathMatches[k+1] } } if match == nil { match = &RouteMatch{Route: r, Handler: r.handler} } if redirectURL != "" { match.Handler = http.RedirectHandler(redirectURL, 301) } ctx.Set(req, vars) routeCtx.Set(req, match.Route) return match, true }