Example #1
0
func (ui *UIHandler) serveFileTree(rw http.ResponseWriter, req *http.Request) {
	if ui.Storage == nil {
		http.Error(rw, "No BlobRoot configured", 500)
		return
	}

	suffix := req.Header.Get("X-PrefixHandler-PathSuffix")
	m := treePattern.FindStringSubmatch(suffix)
	if m == nil {
		httputil.ErrorRouting(rw, req)
		return
	}

	blobref := blobref.Parse(m[1])
	if blobref == nil {
		http.Error(rw, "Invalid blobref", 400)
		return
	}

	fth := &FileTreeHandler{
		Fetcher: ui.Storage,
		file:    blobref,
	}
	fth.ServeHTTP(rw, req)
}
Example #2
0
func gamesPost(w http.ResponseWriter, r *http.Request, u *user.User, c appengine.Context) {

	game := Game{
		P1:     r.FormValue("player1"),
		P2:     r.FormValue("player2"),
		Played: datastore.SecondsToTime(time.Seconds()),
	}
	scorefields := map[string]int{
		"Player1score": 0,
		"Player2score": 0,
	}
	for k, _ := range scorefields {
		score, err := strconv.Atoi(r.FormValue(k))
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		scorefields[k] = score
	}
	game.P1score = scorefields["Player1score"]
	game.P2score = scorefields["Player2score"]

	_, err := datastore.Put(c, datastore.NewIncompleteKey("Game"), &game)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	rurl := fmt.Sprintf("http://%v/", r.Host)
	w.Header().Set("Location", rurl)
	w.WriteHeader(http.StatusFound)
}
Example #3
0
func c1LoginHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if l, err := c1IsLoggedIn(c); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	} else if l {
		///    http.Redirect(w, r, "/", http.StatusFound)
		http.Redirect(w, r, "/index", http.StatusFound)
		return
	}

	if r.Method == "GET" {
		w.Write([]byte(
			"<html><body><form action='/c1Login' method='POST'>" +
				"<input type='text' name='usr'></input>" +
				"<input type='password' name='pwd'></input>" +
				"<input type='submit' value='Submit'></input>" +
				"</form></body></html>"))
		return
	} else if r.Method == "POST" {
		usr := r.FormValue("usr")
		pwd := r.FormValue("pwd")
		_, err := C1Login(c, usr, pwd)
		if err == C1AuthError {
			http.Error(w, err.String(), http.StatusUnauthorized)
			return
		}
		http.Redirect(w, r, "/index", http.StatusFound)
		///    http.Redirect(w, r, "/", http.StatusFound)
	}
}
Example #4
0
func main(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	tok, err := AddClient(c, u.Id)
	if err != nil {
		http.Error(w, err.String(), 500)
		return
	}

	err = mainTemplate.Execute(w, map[string]string{
		"token":        tok,
		"client_id":    u.Id,
		"client_email": u.Email,
	})

	if err != nil {
		c.Errorf("mainTemplate: %v", err)
	}

}
Example #5
0
func myWidgets(w http.ResponseWriter, r *http.Request) {
	var err os.Error
	ctx := appengine.NewContext(r)

	page, err := template.Parse(myWidgetTemplate, nil)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	data := myWidgetData{
		CSS:    commonCSS(),
		Header: header(ctx),
	}

	data.Widget, err = LoadWidgets(ctx)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	if len(r.FormValue("ids_only")) > 0 {
		w.Header().Set("Content-Type", "text/plain")
		for _, widget := range data.Widget {
			fmt.Fprintln(w, widget.ID)
		}
		return
	}

	page.Execute(w, data)
}
Example #6
0
func testHandler(w http.ResponseWriter, r *http.Request) {
	// read user code
	userCode := new(bytes.Buffer)
	defer r.Body.Close()
	if _, err := userCode.ReadFrom(r.Body); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	// put user code in harness
	t := step1.Test
	t.UserCode = userCode.String()
	code := new(bytes.Buffer)
	if err := TestHarness.Execute(code, t); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	// run code
	out, err := run(code.String())
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	if out.Output == t.Expect {
		fmt.Fprint(w, "Well done!")
	} else {
		fmt.Fprintf(w, "Not quite.\n\n%s", out.Errors)
	}
}
Example #7
0
func addWidget(w http.ResponseWriter, r *http.Request) {
	var err os.Error
	if fixup == nil {
		fixup, err = regexp.Compile(`[^A-Za-z0-9\-_. ]`)
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
	}

	ctx := appengine.NewContext(r)
	name := fixup.ReplaceAllString(r.FormValue("name"), "")

	if len(name) == 0 {
		http.Error(w, "Invalid/no name provided", http.StatusInternalServerError)
		return
	}

	widget := NewWidget(ctx, name)

	err = widget.Commit()
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/widget/list", http.StatusFound)
}
Example #8
0
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)
	resp, err := client.Get("http://en.wikipedia.org/wiki/Special:Random")
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}

	body := resp.Body
	var allData []byte
	allData = make([]byte, resp.ContentLength)
	body.Read(allData)

	firstLine := getFirstLine(string(allData))
	url := getUrl(string(allData))

	if firstLine == "" {
		c.Errorf("Saw empty first line for url: %s", url)
	}

	data := map[string]string{
		"firstLine": firstLine,
		"url":       url,
	}

	err2 := mainPageTemplate.Execute(w, data)
	if err2 != nil {
		http.Error(w, err2.String(), http.StatusInternalServerError)
	}
}
Example #9
0
func (authData *validatorImpl) LoginHandler(w http.ResponseWriter, r *http.Request) {
	client := r.FormValue("client")
	token := r.FormValue("token")

	if client == "" || token == "" {
		w.Write([]byte(loginHtml))
		return
	}

	existingToken, found := authData.tokenMap[client]
	if !found {
		http.Error(w, "Invalid auth token", http.StatusForbidden)
		return
	}
	if token != existingToken {
		log.Printf("Invalid token: %s != %s", token, existingToken)
		http.Error(w, "Invalid auth token", http.StatusForbidden)
		return
	}

	// Set cookies.
	clientCookie := &http.Cookie{Name: "client", Value: client, Secure: true}
	http.SetCookie(w, clientCookie)

	tokenCookie := &http.Cookie{Name: "token", Value: token, Secure: true}
	http.SetCookie(w, tokenCookie)

	w.Write([]byte("Login successful"))
}
func registration(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	u := User{
		Name:      "TestHendrik",
		StartDate: datastore.SecondsToTime(time.Seconds()),
	}

	if g := user.Current(c); g != nil {
		var u2 User
		u.Account = g.String()
		if err := datastore.Get(c, datastore.NewKey("user", g.String(), 0, nil), &u2); err == datastore.ErrNoSuchEntity {
			key, err := datastore.Put(c, datastore.NewKey("user", u.Account, 0, nil), &u)
			if err != nil {
				http.Error(w, err.String(), http.StatusInternalServerError)
				return
			}
			fmt.Fprintf(w, "User %q stored %q", u.Account, key)
			return
		} else {
			fmt.Fprintf(w, "User %q  is already logged in", g.String())
			return
		}
	} else {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

}
Example #11
0
// Given a described blob, optionally follows a camliContent and
// returns the file's schema blobref and its fileinfo (if found).
func (pr *publishRequest) fileSchemaRefFromBlob(des *search.DescribedBlob) (fileref *blobref.BlobRef, fileinfo *search.FileInfo, ok bool) {
	if des == nil {
		http.NotFound(pr.rw, pr.req)
		return
	}
	if des.Permanode != nil {
		// TODO: get "forceMime" attr out of the permanode? or
		// fileName content-disposition?
		if cref := des.Permanode.Attr.Get("camliContent"); cref != "" {
			cbr := blobref.Parse(cref)
			if cbr == nil {
				http.Error(pr.rw, "bogus camliContent", 500)
				return
			}
			des = des.PeerBlob(cbr)
			if des == nil {
				http.Error(pr.rw, "camliContent not a peer in describe", 500)
				return
			}
		}
	}
	if des.CamliType == "file" {
		return des.BlobRef, des.File, true
	}
	http.Error(pr.rw, "failed to find fileSchemaRefFromBlob", 404)
	return
}
Example #12
0
func show(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    q := datastore.NewQuery("Guest").Order("Date")
    count, err := q.Count(c)
    if err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }

    guests := make([]Guest, 0, count)
    guest_views :=([]Guest_View, count)
    if keys, err := q.GetAll(c, &guests); err != nil {
        http.Error(w, errString(), http.StatusInternalServerError)
        return
    } else {
        for pos, guest := range guests {
            guest_views[pos].Id = keys[pos].IntID()
            guest_views[pos].Name = guest.Name
            localTime := time.SecondsToLocalTime(int64(guest.Date) / 1000000)
            guest_views[pos].Date = fmt.Sprintf("%04d/%02d/%02d %02d:%02d:%02d", localTime.Year, localTime.Month, localTime.Day, localTime.Hour, localTime.Minute, localTime.Second)
        }
    }

    if err := showHTMLTemplate.Execute(w, guest_views); err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
    }
}
// POST /jobs/id/stop or POST /jobs/id/kill
func (this RestJsonMongo) Act(rw http.ResponseWriter, parts []string, r *http.Request) (item interface{}) {
	logger.Debug("Act(%v):%v", r.URL.Path, parts)

	if len(parts) < 2 {
		if err := this.LoadJson(r, item); err != nil {
			http.Error(rw, err.String(), http.StatusBadRequest)
			return
		} else {
			id := parts[1]
			if err := this.Store.Update(id, item); err != nil {
				http.Error(rw, err.String(), http.StatusBadRequest)
				return
			}
		}
	}

	if this.Target == nil {
		http.Error(rw, fmt.Sprintf("service not found %v", r.URL.Path), http.StatusNotImplemented)
		return
	}

	preq, _ := http.NewRequest(r.Method, r.URL.Path, r.Body)
	proxy := http.NewSingleHostReverseProxy(this.Target)
	go proxy.ServeHTTP(rw, preq)

	return
}
Example #14
0
func view(w http.ResponseWriter, r *http.Request) {

	id, _ := strconv.Atoi(r.FormValue("id"))

	c := appengine.NewContext(r)

	var view detail_view

	// グループ情報を取得
	if group, err := model.GetGroup(c, id); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	} else {
		view.Group = group
	}

	// メンバー情報を取得
	if memberlist, err := model.MemberList(c, id); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	} else {
		view.Member = memberlist
	}

	// 詳細画面を表示
	if err := detailTemplate.Execute(w, view); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #15
0
func (ui *UIHandler) serveDownload(rw http.ResponseWriter, req *http.Request) {
	if ui.Storage == nil {
		http.Error(rw, "No BlobRoot configured", 500)
		return
	}

	suffix := req.Header.Get("X-PrefixHandler-PathSuffix")
	m := downloadPattern.FindStringSubmatch(suffix)
	if m == nil {
		httputil.ErrorRouting(rw, req)
		return
	}

	fbr := blobref.Parse(m[1])
	if fbr == nil {
		http.Error(rw, "Invalid blobref", 400)
		return
	}

	dh := &DownloadHandler{
		Fetcher: ui.Storage,
		Cache:   ui.Cache,
	}
	dh.ServeHTTP(rw, req, fbr)
}
Example #16
0
func join(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	r.ParseForm()
	// TODO check table arg
	state, err := joinTable(c, r.Form["table"][0], u.String())
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	var b []byte
	b, err = json.Marshal(state)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "%s", b)
}
Example #17
0
// Handle maps the given handler (typically a *Resource) at the given path and
// provides a first level of logging, locking, and access control for the
// resource.
//
// A request for POST, PUT, DELETE, or PATCH on a ReadOnly resource will result
// in an HTTP Forbidden response.  A CONNECT or other request will also
// generate the necessary HTTP error code.
//
// A request for OPTIONS on a resource will generate a reply containing an
// Allow header listing the available methods for that resource.  If the
// resource is readonly, only "safe" methods will be listed.  The ServeREST
// method will still be called, so this header may be modified by the handler.
//
// If the method is a "safe" method (e.g. GET), the resource is locked for
// reading.  If the method is an "unsafe" method (e.g. PUT), the resource is
// locked for writing.  The resource is unlocked when the request handling
// completes.
//
// Errors returned by rhe ServeREST function of the handler are sent to the
// client.  By default, these are sent with an HTTP Internal Server Error
// response, but if the error has an ErrorCode() int method, the return value
// of that method will be used is the status code instead.
func Handle(path string, handler Handler) {
	DefaultServeMux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
		log := func(message string) {
			log.Printf("rest: %s: %s", r.RemoteAddr, message)
		}

		var res *Resource
		if r, ok := handler.(*Resource); ok {
			res = r
		}

		switch r.Method {
		case "POST", "PUT", "DELETE", "PATCH":
			if res != nil {
				if res.ro {
					log("attempt to modify read-only resource " + r.URL.Path + " blocked")
					http.Error(w, "Read-Only Resource", http.StatusForbidden)
					return
				}
				res.lock.Lock()
				defer res.lock.Unlock()
			}
		case "CONNECT":
			log("CONNECT attempt blocked")
			http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
			return
		case "GET", "HEAD":
			if res != nil {
				res.lock.RLock()
				defer res.lock.RUnlock()
			}
		case "OPTIONS":
			allow := []string{"OPTIONS", "HEAD", "GET", "POST", "PATCH", "PUT", "DELETE"}
			if res != nil && res.ro {
				allow = allow[:3]
			}
			w.Header().Set("Allow", strings.Join(allow, ", "))
		default:
			log("unknown method: " + r.Method)
			http.Error(w, "Not Implemented", http.StatusNotImplemented)
			return
		}

		err := handler.ServeREST(w, r)
		if err == nil {
			w.WriteHeader(http.StatusOK)
			return
		}

		log(err.String())

		status := http.StatusInternalServerError
		if err, ok := err.(ErrorCoder); ok {
			status = err.ErrorCode()
		}

		http.Error(w, err.String(), status)
	})
}
Example #18
0
func (dh *DownloadHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, file *blobref.BlobRef) {
	if req.Method != "GET" && req.Method != "HEAD" {
		http.Error(rw, "Invalid download method", 400)
		return
	}

	fetchSeeker, err := dh.storageSeekFetcher()
	if err != nil {
		http.Error(rw, err.String(), 500)
		return
	}

	fr, err := schema.NewFileReader(fetchSeeker, file)
	if err != nil {
		http.Error(rw, "Can't serve file: "+err.String(), 500)
		return
	}
	defer fr.Close()

	schema := fr.FileSchema()
	rw.Header().Set("Content-Length", fmt.Sprintf("%d", schema.SumPartsSize()))

	// TODO: fr.FileSchema() and guess a mime type?  For now:
	mimeType := "application/octet-stream"
	if dh.ForceMime != "" {
		mimeType = dh.ForceMime
	}
	rw.Header().Set("Content-Type", mimeType)

	if req.Method == "HEAD" {
		vbr := blobref.Parse(req.FormValue("verifycontents"))
		if vbr == nil {
			return
		}
		hash := vbr.Hash()
		if hash == nil {
			return
		}
		io.Copy(hash, fr) // ignore errors, caught later
		if vbr.HashMatches(hash) {
			rw.Header().Set("X-Camli-Contents", vbr.String())
		}
		return
	}

	n, err := io.Copy(rw, fr)
	log.Printf("For %q request of %s: copied %d, %v", req.Method, req.URL.RawPath, n, err)
	if err != nil {
		log.Printf("error serving download of file schema %s: %v", file, err)
		return
	}
	if size := schema.SumPartsSize(); n != int64(size) {
		log.Printf("error serving download of file schema %s: sent %d, expected size of %d",
			file, n, size)
		return
	}

}
Example #19
0
func hookCountable(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	path := strings.Split(strings.Trim(r.URL.Path, "/"), "/", -1)
	if len(path) < 3 {
		http.Error(w, "/hook/{type}/{widget} - missing required path segment", http.StatusBadRequest)
		return
	}

	var uniqueKey int64
	var countable string
	switch path[1] {
	case "plusone":
		countable = "Rating"
	case "wontbuild":
		countable = "Broken"
	case "compile":
		countable = "Build"
		uniqueKey = int64(now())
	case "commit":
		countable = "Commit"
		uniqueKey = int64(now())
	default:
		http.Error(w, "/hook/{type}/{widget} - unknown type", http.StatusBadRequest)
		return
	}

	widget := path[2]
	if len(widget) != 32 {
		http.Error(w, "Invalid widget id: "+widget, http.StatusBadRequest)
		return
	}
	if _, err := LoadWidget(ctx, widget); err != nil {
		http.Error(w, "Unknown widget id: "+widget, http.StatusBadRequest)
		return
	}

	ip := r.RemoteAddr
	if ip == "" {
		ip = "devel"
	}

	keyhash := Hashf("IP=%s|Unique=%d", ip, uniqueKey)
	obj := NewCountable(ctx, countable, widget, keyhash)
	if err := obj.Commit(); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	refreshWidget(w, r, widget)

	// TODO(kevlar): Referer?
	//http.Redirect(w, r, "/widget/list", http.StatusFound)

	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "OK")
}
Example #20
0
func TemplateRender(w http.ResponseWriter, filename string, context interface{}) {
	t, err := template.ParseFile(filename, nil)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
	if err := t.Execute(w, context); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #21
0
func updateWidget(w http.ResponseWriter, r *http.Request) {
	var err os.Error
	ctx := appengine.NewContext(r)

	fix := func(formname string) string {
		raw := r.FormValue(formname)
		if strings.Contains(raw, "'") {
			ctx.Warningf("Hacking attempt: %#q", raw)
			return ""
		}
		url, err := http.ParseURLReference(raw)
		if err != nil {
			ctx.Infof("Bad URL: %#q", raw)
			return ""
		}
		if scheme := strings.ToLower(url.Scheme); scheme != "http" && scheme != "https" {
			ctx.Infof("Bad scheme: %%q", scheme)
			return ""
		}
		return url.String()
	}

	bug := fix("bug")
	home := fix("home")
	source := fix("source")

	path := strings.Split(strings.Trim(r.URL.Path, "/"), "/", -1)
	if cnt := len(path); cnt != 3 {
		http.Error(w, "ID required", http.StatusBadRequest)
		return
	}

	widgethash := path[2]
	if len(widgethash) != 32 {
		http.Error(w, "Invalid widget id: "+widgethash, http.StatusBadRequest)
		return
	}

	widget, err := LoadWidget(ctx, widgethash)
	if err != nil {
		http.Error(w, "Unknown widget id: "+widgethash, http.StatusBadRequest)
		return
	}

	widget.BugURL = bug
	widget.HomeURL = home
	widget.SourceURL = source

	err = widget.Commit()
	if err != nil {
		http.Error(w, "Error comitting: "+err.String(), http.StatusBadRequest)
		return
	}

	http.Redirect(w, r, "/widget/list", http.StatusFound)
}
Example #22
0
func renderPage(w http.ResponseWriter, data map[string]string) {
	mainPageTemplate, templateErr := template.ParseFile("hvadsigeralex/templates/index.html")
	if templateErr != nil {
		http.Error(w, templateErr.String(), http.StatusInternalServerError)
	}
	err := mainPageTemplate.Execute(w, data)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #23
0
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
	t, err := template.ParseFile(tmpl+".html", nil)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	err = t.Execute(w, p)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #24
0
func spamham(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	requireLogin(c, w, r.URL.String())
	mainPageTemplate, templateErr := template.ParseFile("templates/spamham.html")
	if templateErr != nil {
		http.Error(w, templateErr.String(), http.StatusInternalServerError)
	}
	err := mainPageTemplate.Execute(w, nil)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #25
0
func callback(w http.ResponseWriter, r *http.Request) {
  post := new(eventReq)
  if err := (*fhttp.JsonRequest)(r).Extract(eventReq); err != nil {
    http.Error(w, "Invalid JSON", http.StatusBadRequest)
    return
  }
  req, err := http.NewRequest("GET", "https://api.stripe.com/v1/events/" + eventReq.Id, nil)
  if err != nil {
    http.Error(w, "Could not create request: " + err.String(), http.StatusInternalServerError)
  }
  req.SetBasicAuth(
}
Example #26
0
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	q := datastore.NewQuery("Greeting").Order("-Date").Limit(10)
	greetings := make([]Greeting, 0, 10)
	if _, err := q.GetAll(c, &greetings); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	if err := guestbookTemplate.Execute(w, greetings); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #27
0
func searchHandler(w http.ResponseWriter, r *http.Request) {
	context := &Search{}
	// prepare the template
	t, err := template.ParseFile("template/search.html")
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
	context.T = t
	ae := appengine.NewContext(r)
	query := r.FormValue("q")
	queryLength := len([]int(query)) // unicode length
	// max 8 letters
	if queryLength > 8 {
		query = query[0:8]
		http.Redirect(w, r, fmt.Sprintf("search?q=%s", query), 302)
		return
	}
	// lowercase only
	if query != strings.ToLower(query) {
		http.Redirect(w, r, fmt.Sprintf("search?q=%s", strings.ToLower(query)), 302)
		return
	}
	context.Q = query

	hashTable := make(map[string]byte, 0)

	if 0 != queryLength {
		if queryLength > 8 {
			query = query[0:8]
		}
		// make sure enable is loaded
		var e *word.Enable
		var err os.Error
		if e, err = loadEnable(); err != nil {
			ae.Errorf("%v", err)
		}
		channel := word.StringPermutations(query)
		for p := range channel {
			if valid := e.WordIsValid(p); !valid {
				continue
			}
			if _, inHash := hashTable[p]; !inHash {
				context.Permutations = append(context.Permutations, p)
				hashTable[p] = 1
			}
		}
	}
	// display template
	if err := context.T.Execute(w, context); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #28
0
func index(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	q := datastore.NewQuery("Fact").Order("-AddDate").Limit(10)
	facts := make([]FactModel, 0, 10)
	for t := q.Run(c); ; {
		var x Fact
		key, err := t.Next(&x)
		if err == datastore.Done {
			break
		}
		if err != nil {
			http.Error(w, err.String(), http.StatusInternalServerError)
			return
		}
		tags := getTags(c, key)

		fk := FactModel{
			Key:        key.String(),
			Title:      x.Title,
			SourceUrl:  x.SourceUrl,
			SourceName: x.SourceName,
			Details:    x.Details,
			User:       x.User,
			Tags:       tags,
		}
		facts = append(facts, fk)
	}
	p := PageData{
		Title:      "Faktum",
		Facts:      facts,
		SourceURL:  r.FormValue("source_url"),
		SourceName: r.FormValue("source_name"),
		Details:    r.FormValue("details"),
		FactTitle:  r.FormValue("title"),
		User:       u.String(),
	}

	if err := indexTmpl.Execute(w, p); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #29
0
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	query := datastore.NewQuery("Events").Filter("ClosedDate <",
		time.Seconds()).Order("ClosedDate")
	events := make([]MailEvent, 0, 100)
	if _, err := query.GetAll(c, &events); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	if err := rootTemplate.Execute(w, events); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
	}
}
Example #30
0
func listTables(w http.ResponseWriter, r *http.Request) {
	tables, err := getTables(appengine.NewContext(r))
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	b, err := json.Marshal(tables)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "%s", b)
}