func serveSymbol(req *web.Request) { var p []byte if req.Method == "POST" { var err os.Error p, err = req.BodyBytes(-1) if err != nil { req.Error(web.StatusInternalServerError, err) return } } else { p = []byte(req.URL.RawQuery) } w := respondText(req) io.WriteString(w, "num_symbols: 1\n") for len(p) > 0 { var a []byte if i := bytes.IndexByte(p, '+'); i >= 0 { a = p[:i] p = p[i+1:] } else { a = p p = nil } if pc, _ := strconv.Btoui64(string(a), 0); pc != 0 { if f := runtime.FuncForPC(uintptr(pc)); f != nil { fmt.Fprintf(w, "%#x %s\n", pc, f.Name()) } } } }
// authCallbackHandler handles redirect from Facebook OAuth2 authorization page. func authCallbackHandler(req *web.Request) { code := req.Param.Get("code") if code == "" { // should display error_reason req.Redirect("/", false) return } f, err := getUrlEncodedForm("https://graph.facebook.com/oauth/access_token", web.NewValues( "client_id", appID, // defined in settings.go "client_secret", appSecret, // defined in settings.go "redirect_uri", req.URL.Scheme+"://"+req.URL.Host+"/callback", "code", code)) if err != nil { req.Error(web.StatusInternalServerError, err) return } token := f.Get("access_token") expires := f.Get("expires") if expires == "" { expires = "3600" } maxAge, err := strconv.Atoi(expires) if err != nil { maxAge = 3600 } else { maxAge -= 30 // fudge } req.Redirect("/", false, web.HeaderSetCookie, web.NewCookie("fbtok", token). MaxAge(maxAge-30).String()) }
// Run simply runs the generator. func (c *DummyCache) Run(req *web.Request, fnGenerate func(w io.Writer) bool) { var buf = &bytes.Buffer{} if fnGenerate(buf) { req.Respond(web.StatusOK, web.HeaderContentType, "text/html").Write(buf.Bytes()) } else { req.Error(web.StatusNotFound, os.NewError("Not Found.")) } }
func pathHandler(req *web.Request, targetPattern string) { if newPath := req.Param.Get("path"); newPath == "" { req.Error(web.StatusNotFound, os.NewError("Not Found.")) } else { newUrl := fmt.Sprintf(targetPattern, req.URL.Scheme, req.URL.Host, newPath) req.Redirect(newUrl, true) } }
func ServeWeb(req *web.Request) { b, err := json.MarshalIndent(vars, "", " ") if err != nil { req.Error(web.StatusInternalServerError, err) return } req.Respond(web.StatusOK, web.HeaderContentType, "application/json; charset=utf-8").Write(b) }
// login redirects the user to the Twitter authorization page. func login(req *web.Request) { callback := req.URL.Scheme + "://" + req.URL.Host + "/callback" temporaryCredentials, err := oauthClient.RequestTemporaryCredentials(http.DefaultClient, callback) if err != nil { req.Error(web.StatusInternalServerError, err) return } req.Redirect(oauthClient.AuthorizationURL(temporaryCredentials), false, web.HeaderSetCookie, credentialsCookie("tmp", temporaryCredentials, 0)) }
func multipartHandler(req *web.Request) { files, err := web.ParseMultipartForm(req, -1) if err != nil { req.Error(web.StatusBadRequest, err) return } w := req.Respond(web.StatusOK, web.HeaderContentType, "text/html; charset=utf-8") if err := templates.ExecuteTemplate(w, "home.html", map[string]interface{}{"req": req, "files": files}); err != nil { log.Print(err) } }
func saveHandler(req *web.Request) { body := req.Param.Get("body") title := req.URLParam["title"] p := &page{Title: title, Body: []byte(body)} err := p.save() if err != nil { req.Error(web.StatusInternalServerError, err) return } req.Redirect("/view/"+title, false) }
func serveProfile(req *web.Request) { sec, _ := strconv.ParseInt(req.Param.Get("seconds"), 10, 64) if sec == 0 { sec = 30 } if err := pprof.StartCPUProfile(&lazyResponder{req, nil}); err != nil { req.Error(web.StatusInternalServerError, err) return } time.Sleep(time.Duration(sec) * time.Second) pprof.StopCPUProfile() }
func serveProfile(req *web.Request) { sec, _ := strconv.Atoi64(req.Param.Get("seconds")) if sec == 0 { sec = 30 } if err := pprof.StartCPUProfile(&lazyResponder{req, nil}); err != nil { req.Error(web.StatusInternalServerError, err) return } time.Sleep(sec * 1e9) pprof.StopCPUProfile() }
// ServeWeb serves profile data for the pprof tool. func ServeWeb(req *web.Request) { switch { case strings.HasSuffix(req.URL.Path, "/pprof/cmdline"): io.WriteString(respondText(req), strings.Join(os.Args, "\x00")) case strings.HasSuffix(req.URL.Path, "/pprof/profile"): serveProfile(req) case strings.HasSuffix(req.URL.Path, "/pprof/heap"): pprof.WriteHeapProfile(respondText(req)) case strings.HasSuffix(req.URL.Path, "/pprof/symbol"): serveSymbol(req) default: req.Error(web.StatusNotFound, nil) } }
// home handles requests to the home page. func homeHandler(req *web.Request) { token, err := accessToken(req) if err != nil { loggedOutHandler(req) return } feed, err := getJSON("https://graph.facebook.com/me/home", web.NewValues("access_token", token)) if err != nil { req.Error(web.StatusInternalServerError, err, web.HeaderSetCookie, web.NewCookie("fbtok", "").Delete().String()) return } homeTemplate.respond(req, web.StatusOK, feed) }
func handleSign(r *web.Request) { c := gae.Context(r) g := &Greeting{ Content: r.Param.Get("content"), Date: datastore.SecondsToTime(time.Seconds()), } if u := user.Current(c); u != nil { g.Author = u.String() } if _, err := datastore.Put(c, datastore.NewIncompleteKey("Greeting"), g); err != nil { r.Error(web.StatusInternalServerError, err) return } r.Redirect("/", false) }
// Run looks up the page in the cache and generates it if it does not exist, // placing it in the cache afterwards. func (c *Cache) Run(req *web.Request, fnGenerate func(w io.Writer) bool) { cached, found := c.items[req.URL.String()] if !found { var buf = &bytes.Buffer{} if !fnGenerate(buf) { req.Error(web.StatusNotFound, os.NewError("Not Found.")) return } cached = buf.Bytes() c.items[req.URL.String()] = cached } req.Respond(web.StatusOK, web.HeaderContentType, "text/html").Write(cached) }
func handleMainPage(r *web.Request) { c := gae.Context(r) q := datastore.NewQuery("Greeting").Order("-Date").Limit(10) var gg []*Greeting _, err := q.GetAll(c, &gg) if err != nil { r.Error(web.StatusInternalServerError, err) return } w := r.Respond(200, "Content-Type", "text/html") if err := mainPage.Execute(w, map[string]interface{}{ "xsrf": r.Param.Get("xsrf"), "gg": gg}); err != nil { c.Logf("%v", err) } }
func (ph *pageHandler) ServeWeb(req *web.Request) { // Render page. fmt.Println(req.URL.Path) post, found := ph.context.Db.GetPage(req.URL.Path) if !found { req.Error(web.StatusNotFound, os.NewError("Not Found.")) return } local_context := *ph.context local_context.Title = post.Title local_context.Path = post.CanonicalBlogUrl.String() + post.CanonicalPath var content bytes.Buffer renderPost(&content, &local_context, post, post.CommentOnPage) // Render page. templates["main"].Execute( req.Respond(web.StatusOK, web.HeaderContentType, "text/html"), makeTemplateParams(&local_context, content.Bytes())) }
// home handles requests to the home page. func home(req *web.Request) { token, err := credentials(req, "tok") if err != nil { homeLoggedOut(req) return } param := make(web.Values) url := "http://api.twitter.com/1/statuses/home_timeline.json" oauthClient.SignParam(token, "GET", url, param) url = url + "?" + param.FormEncodedString() resp, err := http.Get(url) if err != nil { req.Error(web.StatusInternalServerError, err) return } defer resp.Body.Close() if resp.StatusCode != 200 { req.Error(web.StatusInternalServerError, os.NewError(fmt.Sprint("Status ", resp.StatusCode))) return } var d interface{} err = json.NewDecoder(resp.Body).Decode(&d) if err != nil { req.Error(web.StatusInternalServerError, err) return } homeTempl.Execute(req.Respond(web.StatusOK, web.HeaderContentType, web.ContentTypeHTML), d) }
// authCallback handles OAuth callbacks from Twitter. func authCallback(req *web.Request) { temporaryCredentials, err := credentials(req, "tmp") if err != nil { req.Error(web.StatusNotFound, err) return } s := req.Param.Get("oauth_token") if s == "" { req.Error(web.StatusNotFound, os.NewError("main: no token")) return } if s != temporaryCredentials.Token { req.Error(web.StatusNotFound, os.NewError("main: token mismatch")) return } tokenCredentials, _, err := oauthClient.RequestToken(http.DefaultClient, temporaryCredentials, req.Param.Get("oauth_verifier")) if err != nil { req.Error(web.StatusNotFound, err) return } req.Redirect("/", false, web.HeaderSetCookie, credentialsCookie("tok", tokenCredentials, 30), web.HeaderSetCookie, web.NewCookie("tmp", "").Delete().String()) }