func handlePost(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if r.Method != "GET" || r.URL.Path != "/post" { serve404(w) return } c := appengine.NewContext(r) u := user.Current(c) if u == nil { url, err := user.LoginURL(c, r.URL.String()) if err != nil { serveError(c, w, err) return } w.Header().Set("Location", url) w.WriteHeader(http.StatusFound) return } if !user.IsAdmin(c) { serve404(w) return } uploadURL, err := blobstore.UploadURL(c, "/upload", nil) if err != nil { serveError(c, w, err) return } err = postTemplate.Execute(w, uploadURL) if err != nil { serveError(c, w, err) } }
func SearchHandler(w http.ResponseWriter, r *http.Request) { data := make(map[string]string) c := appengine.NewContext(r) u := user.Current(c) if u != nil { data["Email"] = u.String() upload_url, upload_err := blobstore.UploadURL(c, "/upload") if upload_err != nil { c.Logf("blob store is disabled? %v", upload_err) data["Upload_Action"] = "/upload" } else { data["Upload_Action"] = upload_url.String() } } else { url, err := user.LoginURL(c, r.URL.String()) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } data["Login_url"] = url } data["Base_person"] = "{\"name\": \"James Morrison\", \"Date of Birth\": [1981, 10, 2]}" template_err := searchTemplate.Execute(w, data) if template_err != nil { log.Print("Error rendering template ", template_err) } }
func Index(w http.ResponseWriter, r *http.Request) { server := plate.NewServer() photos, err := photos_help.GetAll(r) if err != nil { photos = nil } albums, err := albums_help.GetAll(r) if err != nil { albums = nil } c := appengine.NewContext(r) uploadURL, _ := blobstore.UploadURL(c, "/admin/photos", nil) mux := menuMux.New() mux.AdminMenu("Photos") t, _ := server.Template(w) t.Bag["MenuItems"] = mux.GetItems() t.Bag["Photos"] = photos t.Bag["Albums"] = albums t.Bag["UploadURL"] = uploadURL t.Layout = "templates/admin/layout.html" files := []string{"templates/admin/sidebar.html", "templates/admin/photos/index.html"} t.DisplayMultiple(files) }
// Generates an image upload url for the blobstore and returns it as a string func GetBlobstoreUploadPath(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) userKeyName := vars["userID"] ctx := appengine.NewContext(r) // Check to see if the page user is the same as the logged in user userIsOwner := utils.IsOwner(userKeyName, ctx) if !userIsOwner { api.ApiErrorResponse(w, "You cannot edit other profiles.", http.StatusInternalServerError) return } returnPath := "/user/" + userKeyName // The autosaved thumbnail images need to be POSTed to specific appengine blobstore "action" paths. // Have to specify a path to return to after the post succeeds imageUploadUrl, err := blobstore.UploadURL(ctx, returnPath, nil) if err != nil { api.ApiErrorResponse(w, "Could not generate blobstore upload: "+err.Error(), http.StatusInternalServerError) return } // Need to return the uploadUrl to use to post the image to uploadUrl := bytes.NewBufferString(imageUploadUrl.Path) io.Copy(w, uploadUrl) return }
func Edit(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) { c := appengine.NewContext(req) var b banner.Banner intID, err := strconv.Atoi(params["id"]) if err == nil { b.ID = int64(intID) } if b.ID > 0 { if err := b.Get(c); err != nil { http.Redirect(rw, req, "/admin?error="+err.Error(), http.StatusFound) return } } uploadURL, err := blobstore.UploadURL(c, "/admin/banners/"+strconv.Itoa(intID), nil) if err != nil { http.Redirect(rw, req, "/admin?error="+err.Error(), http.StatusFound) return } bag := make(map[string]interface{}, 0) bag["Host"] = req.URL.Host bag["Admin"] = true bag["Banner"] = b bag["URL"] = uploadURL bag["ActiveNav"] = "banners" r.HTML(200, "admin/banners/edit", bag) return }
//Upload renders the new presentation upload page. func Upload(c util.Context) (err error) { uploadURL, err := blobstore.UploadURL(c, "/admin/presentation/upload", nil) if err != nil { return } acts, err := activation.GetAfterTime(time.Now(), c) if err != nil { return } type actWithName struct { A *activation.Activation P *presentation.Presentation } ans := make([]actWithName, len(acts)) for i, a := range acts { pk := a.Presentation var p *presentation.Presentation p, err = presentation.GetByKey(pk, c) if err != nil { c.Errorf("Could not load presentation: %v", err) continue } ans[i] = actWithName{a, p} } util.RenderLayout("upload.html", "Nahrať prezentáciu", struct { UploadURL *url.URL Ans []actWithName }{uploadURL, ans}, c) return }
func fileUpload(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) // New FileData fileData := new(FileData) // Get upload url uploadURL, err := blobstore.UploadURL(c, "/file?action=uploadProcess", nil) if err != nil { serveError(c, w, err) return } fileData.PostUrl = uploadURL.String() // New PageSetting pageSetting := new(PageSetting) // Setting pageSetting pageSetting.Title = "File Upload - " + config.Title pageSetting.Layout = "column1" pageSetting.ShowSidebar = false // New PageData pageData := &PageData{File: *fileData} // New Page page := NewPage(pageSetting, pageData) // Render page page.Render("file/upload", w) }
func UploadUrl(c mpg.Context, w http.ResponseWriter, r *http.Request) { uploadURL, err := blobstore.UploadURL(c, routeUrl("import-opml"), nil) if err != nil { serveError(w, err) return } w.Write([]byte(uploadURL.String())) }
// Uploads a file to the blobstore func uploadFile(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadURL, _ := blobstore.UploadURL(c, "/admin/files/handleUpload", nil) passedTemplate := new(bytes.Buffer) template.Must(template.ParseFiles("statuscode.ch/files/templates/upload.html")).Execute(passedTemplate, uploadURL) render.Render(w, r, passedTemplate) }
func authUpload(pfc *PFContext) (interface{}, error) { c := pfc.C if uploadURL, err := blobstore.UploadURL(c, "/import", nil); err != nil { return nil, err } else { return map[string]string{"uploadUrl": uploadURL.String()}, nil } }
func uploadInstructions(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/upload", nil) w.Header().Set("Content-Type", "text/html") err = templates.ExecuteTemplate(w, "upload", uploadURL) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
func submitUpload(c appengine.Context, w http.ResponseWriter, r *http.Request) { // c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/blob2/processing-new-upload", nil) util_err.Err_http(w, r, err, false) w.Header().Set("Content-type", "text/html; charset=utf-8") err = upload2.Execute(w, uploadURL) util_err.Err_http(w, r, err, false) }
func renderBillForm(ctx *Context, errs []string) error { uploadURL, err := blobstore.UploadURL(ctx.c, "/admin/bill/create", nil) if err != nil { return err } vendors, err := ctx.GetAllVendors() if err != nil { return err } return ctx.renderAdmin(newBillTmpl, NewBillForm{&Bill{}, errs, vendors, uploadURL}) }
// Get an URL for uploading a file to a visualization func getVisualizationFileUploadUrl(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) vars := mux.Vars(r) uploadUrl, err := blobstore.UploadURL(c, "/api/visualizations/"+vars["key"]+"/files/upload", nil) if err != nil { common.ServeError(c, w, err) return } common.WriteJson(c, w, uploadUrl.Path) }
func handleRoot(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/upload", nil) if err != nil { serveError(c, w, err) return } w.Header().Set("Content-Type", "text/html") err = rootTemplate.Execute(w, uploadURL) if err != nil { c.Errorf("%v", err) } }
func RestoreForm(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/restore", nil) if err != nil { c.Errorf("%s", err) return } w.Header().Set("Content-Type", "text/html") err = restoreFormTemplate.Execute(w, uploadURL) if err != nil { c.Errorf("%v", err) } }
func handleRoot(ctx *Context, w http.ResponseWriter, r *http.Request) error { uploadURL, err := blobstore.UploadURL(ctx.c, "/upload", nil) if err != nil { return err } ctx.SetTitle("Upload New Bill") render := struct { UploadURL *url.URL }{uploadURL} return ctx.Render(uploadTmpl, render) }
func BlobPage(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/blob/upload", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := htmlTemplate.Execute(w, uploadURL); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
func handleAddItem(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) uploadOptions := &blobstore.UploadURLOptions{MaxUploadBytes: 8000000, MaxUploadBytesPerBlob: 300000} uploadURL, err := blobstore.UploadURL(c, "/upload", uploadOptions) if err != nil { serveError(c, w, err) return } w.Header().Set("Content-Type", "text/html") err = addItemTemplate.Execute(w, uploadURL) if err != nil { c.Errorf("%v", err) } }
func handler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) c.Debugf("00") uploadURL, err := blobstore.UploadURL(c, "/upload", nil) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) c.Errorf("01") return } err = htmlTemplate.Execute(w, uploadURL) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) c.Errorf("02") } }
func newImage(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) if err := users.CheckPerm(w, r, users.OP_UPDATE); err != nil { return } url, err := blobstore.UploadURL(c, "/images/upload", nil) if err != nil { app.ServeError(c, w, err) return } fmt.Fprintf(w, "%s", url) }
func ImageUploadURLHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) imageUploadURL, err := Router.GetRoute("imageUpload").URL() if err != nil { core.HandleError(c, w, err) return } uploadURL, err := blobstore.UploadURL(c, imageUploadURL.Path, nil) if err != nil { core.HandleError(c, w, err) return } core.HandleJSON(c, w, map[string]string{"url": uploadURL.Path}) }
func uploadTranslationHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { panic(&core.Error{http.StatusMethodNotAllowed, ""}) } c := appengine.NewContext(r) uploadURL, err := blobstore.UploadURL(c, "/admin/translation/onUploaded", nil) if err != nil { panic(&core.Error{http.StatusInternalServerError, err.Error()}) } w.Header().Set("Content-Type", "text/html") err = uploadTemplate.Execute(w, uploadURL) if err != nil { panic(&core.Error{http.StatusInternalServerError, err.Error()}) } }
func OfShow(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) if s, ok := sess.IsSess(w, r, c); ok { u, _ := model.GetCta(c, s.User) tc := make(map[string]interface{}) tc["Sess"] = s oferta, _ := model.GetOferta(c, r.FormValue("IdOft")) var id string if oferta.IdEmp != "none" { id = oferta.IdEmp } else { id = r.FormValue("IdEmp") } fd := ofToForm(*oferta) empresa, err := u.GetEmpresa(c, id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tc["Empresa"] = empresa fd.IdEmp = empresa.IdEmp oferta.Empresa = empresa.Nombre fd.Categorias = model.ListCat(c, oferta.IdCat) /* * Se crea el form para el upload del blob */ blobOpts := blobstore.UploadURLOptions{ MaxUploadBytesPerBlob: 1048576, } uploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts) if err != nil { serveError(c, w, err) return } fd.UploadURL = strings.Replace(uploadURL.String(), "http", "https", 1) //fd.UploadURL = uploadURL tc["FormDataOf"] = fd ofadmTpl.ExecuteTemplate(w, "oferta", tc) } else { http.Redirect(w, r, "/r/registro", http.StatusFound) } }
// 画像のアップロード先URL取得 func handleGetImageUrl(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "リクエストエラー", http.StatusBadRequest) return } c := appengine.NewContext(r) uuid := uuid.New() option := blobstore.UploadURLOptions{ StorageBucket: "images", } uploadUrl, err := blobstore.UploadURL(c, "/api/image/upload?key="+uuid, &option) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } iur := ImageUrlResponse{ UploadUrl: uploadUrl.String(), Uuid: uuid, } w.Header().Set("Content-Type", "application/json;charset=utf-8") w.Write(StructToJson(w, iur)) }
// rootHandler returns the landing page, which includes a blobstore upload URL. func rootHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) *appError { logoutURL, err := user.LogoutURL(c, "/") if err != nil { c.Warningf("creating logout URL: %v", err) logoutURL = "/" } uploadURL, err := blobstore.UploadURL(c, "/upload", nil) if err != nil { return appErrorf(err, "could not create blobstore upload url") } username := "******" if u := user.Current(c); u != nil { username = u.String() } err = rootTemplate.Execute(w, &rootTemplateData{ LogoutURL: logoutURL, UploadURL: uploadURL.String(), User: username, }) if err != nil { return appErrorf(err, "could not write template") } return nil }
// Modifica si hay, Crea si no hay // Requiere IdEmp. IdOft es opcional, si no hay lo crea, si hay modifica func OfMod(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) if s, ok := sess.IsSess(w, r, c); ok { u, _ := model.GetCta(c, s.User) tc := make(map[string]interface{}) tc["Sess"] = s var fd FormDataOf var valid bool var ofertamod model.Oferta if r.FormValue("IdOft") == "new" { if empresa, err := u.GetEmpresa(c, r.FormValue("IdEmp")); err != nil { http.Redirect(w, r, "/r/le?d=o", http.StatusFound) } else { tc["Empresa"] = empresa fd.IdEmp = empresa.IdEmp fd.Empresa = empresa.Nombre ofertamod.IdEmp = empresa.IdEmp ofertamod.Oferta = "Nueva oferta" ofertamod.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second) // 5 horas menos ofertamod.FechaHoraPub = time.Now().Add(time.Duration(model.GMTADJ) * time.Second) // 5 horas menos ofertamod.Empresa = strings.ToUpper(empresa.Nombre) ofertamod.BlobKey = "none" o, err := model.NewOferta(c, &ofertamod) model.Check(err) fd = ofToForm(*o) fd.Ackn = "Ok" } } else { /* * Se pide un id oferta que en teoría existe, se consulta y se cambia * Se valida y si no existe se informa un error */ fd, valid = ofForm(w, r, true) ofertamod.IdOft = fd.IdOft ofertamod.IdEmp = fd.IdEmp ofertamod.IdCat = fd.IdCat ofertamod.Oferta = fd.Oferta ofertamod.Descripcion = fd.Descripcion ofertamod.Enlinea = fd.Enlinea ofertamod.Url = fd.Url ofertamod.FechaHoraPub = fd.FechaHoraPub ofertamod.StatusPub = fd.StatusPub //ofertamod.BlobKey = fd.BlobKey ofertamod.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second) oferta, keyOferta := model.GetOferta(c, ofertamod.IdOft) if oferta.IdOft != "none" { ofertamod.BlobKey = oferta.BlobKey ofertamod.Codigo = oferta.Codigo empresa, err := u.GetEmpresa(c, ofertamod.IdEmp) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tc["Empresa"] = empresa fd.IdEmp = empresa.IdEmp fd.Empresa = empresa.Nombre ofertamod.Empresa = strings.ToUpper(empresa.Nombre) emplogo := model.GetLogo(c, empresa.IdEmp) if emplogo != nil { // Tenga lo que tenga, se pasa Sp4 a Oferta.Promocion if emplogo.Sp4 != "" { ofertamod.Promocion = emplogo.Sp4 ofertamod.Descuento = strings.Replace(emplogo.Sp4, "s180", "s70", 1) } } // TODO // es preferible poner un regreso avisando que no existe la empresa if valid { // Ya existe err := model.PutOferta(c, &ofertamod) model.Check(err) // Se borran las relaciones oferta-sucursal err = model.DelOfertaSucursales(c, oferta.IdOft) model.Check(err) // Se crea un mapa de Estados para agregar a OfertaEstado edomap := make(map[string]string, 32) // Se reconstruyen las Relaciones oferta-sucursal con las solicitadas idsucs := strings.Fields(r.FormValue("schain")) for _, idsuc := range idsucs { suc := model.GetSuc(c, u, idsuc, ofertamod.IdEmp) lat, _ := strconv.ParseFloat(suc.Geo1, 64) lng, _ := strconv.ParseFloat(suc.Geo2, 64) var ofsuc model.OfertaSucursal ofsuc.IdOft = ofertamod.IdOft ofsuc.IdSuc = idsuc ofsuc.IdEmp = ofertamod.IdEmp ofsuc.Sucursal = suc.Nombre ofsuc.Lat = lat ofsuc.Lng = lng ofsuc.Empresa = ofertamod.Empresa ofsuc.Oferta = ofertamod.Oferta ofsuc.Descripcion = ofertamod.Descripcion ofsuc.Promocion = ofertamod.Promocion ofsuc.Descuento = ofertamod.Descuento ofsuc.Url = ofertamod.Url ofsuc.StatusPub = ofertamod.StatusPub ofsuc.FechaHora = time.Now().Add(time.Duration(model.GMTADJ) * time.Second) // Se añade el estado de la sucursal al mapa de estados edomap[suc.DirEnt] = oferta.IdOft errOs := ofertamod.PutOfertaSucursal(c, &ofsuc) model.Check(errOs) } // Se limpia la relación OfertaEstado _ = ofertamod.DelOfertaEstado(c) // Se guarda la relación OfertaEstado errOe := ofertamod.PutOfertaEstado(c, edomap) model.Check(errOe) var tituloOf string tituloOf = "" if strings.ToLower(strings.TrimSpace(ofertamod.Oferta)) != "nueva oferta" { tituloOf = ofertamod.Oferta } putSearchData(c, ofertamod.Empresa+" "+tituloOf+" "+ofertamod.Descripcion+" "+r.FormValue("pchain"), keyOferta, oferta.IdOft, ofertamod.IdCat, ofertamod.Enlinea) // Se despacha la generación de diccionario de palabras // Se agrega pcves a la descripción //fmt.Fprintf(w,"http://movil.%s.appspot.com/backend/generatesearch?kind=Oferta&field=Descripcion&id=%s&value=%s&categoria=%s", //appengine.AppID(c), keyOferta.Encode(), ofertamod.Descripcion+" "+r.FormValue("pchain"), strconv.Itoa(ofertamod.IdCat)) //_ = generatesearch(c, keyOferta, ofertamod.Descripcion+" "+r.FormValue("pchain"), ofertamod.IdCat) fd = ofToForm(ofertamod) fd.Ackn = "Ok" } } else { // no existe la oferta } } fd.Categorias = model.ListCat(c, ofertamod.IdCat) /* * Se crea el form para el upload del blob */ blobOpts := blobstore.UploadURLOptions{ MaxUploadBytesPerBlob: 1048576, } uploadURL, err := blobstore.UploadURL(c, "/r/ofimgup", &blobOpts) if err != nil { serveError(c, w, err) return } fd.UploadURL = strings.Replace(uploadURL.String(), "http", "https", 1) //fd.UploadURL = uploadURL tc["FormDataOf"] = fd ofadmTpl.ExecuteTemplate(w, "oferta", tc) } else { http.Redirect(w, r, "/r/registro", http.StatusFound) } /* * FETCH PARA MVBLOB/GENERATE */ cronsecs := 3600 cachename := "mvblob_cron" if _, err := memcache.Get(c, cachename); err == memcache.ErrCacheMiss { slot := strconv.Itoa(cronsecs) item := &memcache.Item{ Key: cachename, Value: []byte(slot), Expiration: time.Duration(cronsecs) * time.Second, } if err := memcache.Add(c, item); err == memcache.ErrNotStored { //c.Errorf("memcache.Add %v : %v", cachename, err) if err := memcache.Set(c, item); err == memcache.ErrNotStored { c.Errorf("Memcache.Set %v : %v", cachename, err) } else { c.Infof("memcached %v", cachename) mvblobFetch(c) } } else { c.Infof("memcached %v", cachename) mvblobFetch(c) } } else { // DO NOTHING } }
func articleAdd(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) if r.Method != "POST" { // Show article add page //因为编辑器的原因 ,在这里就要知道上传的路径 // New FileData fileData := new(FileData) // Get upload url uploadURL, err := blobstore.UploadURL(c, "/file?action=uploadProcess", nil) if err != nil { serveError(c, w, err) return } fileData.PostUrl = uploadURL.String() // New PageSetting pageSetting := new(PageSetting) pageSetting.Title = "Article Manager - Add - " + config.Title pageSetting.Layout = "column1" // New PageData pageData := &PageData{File: *fileData} // New Page page := NewPage(pageSetting, pageData) // Render page err = page.Render("article/add", w) if err != nil { serveError(c, w, err) return } return } // Process post data // Parse form data if err := r.ParseForm(); err != nil { serveError(c, w, err) return } // Custom ID var customID string if r.FormValue("customid") != "" { // Check custom id is exists if checkIdIsExists("Article", r.FormValue("customid"), c) { customID = genID() } else { customID = r.FormValue("customid") } } else { customID = genID() } // Create articleDB articleDB := &ArticleDB{ ID: customID, Date: time.Now(), Title: r.FormValue("title"), Content: []byte(r.FormValue("content")), } // Save to datastore if _, err := datastore.Put(c, datastore.NewIncompleteKey(c, "Article", nil), articleDB); err != nil { serveError(c, w, err) } else { http.Redirect(w, r, "/article?action=manager", http.StatusFound) } }
func EditPost(blog_config map[string]interface{}) func(w http.ResponseWriter, req *http.Request) { template_dir := "templates/" l := func(w http.ResponseWriter, req *http.Request) { appcontext := appengine.NewContext(req) context := map[string]interface{}{} name := req.URL.Query().Get(":name") if name != "" { query := post.GetPostsMatchingUrl(req.URL.Query().Get(":name")) idx, err := post.GetCount(appcontext, query) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } if idx < 1 { context["articlesource"] = "Enter your post here!" context["labels"] = "visible" context["title"] = "No post with that URL found, making new post!" } else { var ps []post.Post keys, err := query.GetAll(appcontext, &ps) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } p := ps[0] tags, err := post.GetTagSlice(appcontext, keys[0]) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } content, err := post.GetPostContent(appcontext, p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } context["articlesource"] = content context["labels"] = strings.Join(tags, ", ") context["title"] = p.Title } } else { context["articlesource"] = "Enter your post here!" context["labels"] = "visible, enter, labels, here" context["title"] = "enter title here" } key := fmt.Sprintf("%v", rand.Int()) tok, err := channel.Create(appcontext, key) if err != nil { http.Error(w, "Couldn't create Channel", http.StatusInternalServerError) appcontext.Errorf("channel.Create: %v", err) return } posturl := "/admin/post?g=" + key uploadurl, err := blobstore.UploadURL(appcontext, posturl, nil) if err != nil { http.Error(w, "Couldn't create blob URL", http.StatusInternalServerError) appcontext.Errorf("blobstore.UploadURL: %v", err) return } context["token"] = tok context["session"] = key context["uploadurl"] = uploadurl total_con := config.Stringify_map(config.Merge(blog_config, context)) c := mustache.RenderFile(template_dir+"edit.html.mustache", total_con) io.WriteString(w, c) if err != nil { appcontext.Errorf("mainTemplate: %v", err) } } return admin_layout(blog_config, l) }
func renderRoot(w http.ResponseWriter, r *http.Request, filter []int) { c := appengine.NewContext(r) //log.Println(c) u := user.Current(c) //need to check if user is logged in so that the login/logout button //is toggled correctly var status *Status = &Status{LoggedIn: false, CurrentUser: nil} if u == nil { status.reset() } else if matched, _ := regexp.MatchString(".*@cornell.edu", u.String()); !matched { status.reset() http.Redirect(w, r, "/logout", http.StatusFound) } else { status.set(true, u) } var now Period e1 := datastore.Get(c, currentSemesterKey(c), &now) log.Printf("The value of now is %v", &now) if e1 != nil { if e1 == datastore.ErrNoSuchEntity { now.Semester = 0 now.Year = 2015 updateSemesterData(c, &now) } else { log.Println("DATASTORE PERIOD ERROR") http.Error(w, e1.Error(), http.StatusInternalServerError) } } var tileKey *datastore.Key if filter != nil { tileKey = tileRootKey(c, filter[0], filter[1]) } else { tileKey = tileRootKey(c, now.Semester, now.Year) } qs := datastore.NewQuery("Tile").Ancestor(tileKey).Order("-LastUpdate") tiles := make([]Tile, 0) if _, err := qs.GetAll(c, &tiles); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } ccperiods := make([]Period, 0) ssperiods := make([]Period, 0) fallqs := datastore.NewQuery("Date").Ancestor(CCRoot(c)).Order("-Semester").Order("-Year") springqs := datastore.NewQuery("Date").Ancestor(SSRoot(c)).Order("-Semester").Order("-Year") fallqs.GetAll(c, &ccperiods) springqs.GetAll(c, &ssperiods) log.Println(ccperiods, ssperiods) //debug //log.Print(tiles) //serve the root template funcMap := template.FuncMap{ "divide": div, "incr": incr, "cong": congz, "ustring": ustring, "contains": contains, "isAdmin": isAdmin, "netID": netID, "format": fmtMembers, } // fp3 := path.Join("templates", "welcome.html") templ := template.Must(template.New("welcome.html").Funcs(funcMap).ParseFiles("templates/welcome.html")) //obtain a new uploadURL for team photo, for blobstore uploadURL, err := blobstore.UploadURL(c, "/submit", nil) if err != nil { panic("oh no!") } w.Header().Set("Content-Type", "text/html") templ.Execute(w, map[string]interface{}{ "Tiles": tiles, "LoggedIn": status, "uploadURL": uploadURL, "ccs": ccperiods, "sss": ssperiods, "now": now, }) }