Пример #1
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)
	}

}
Пример #2
0
func homeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "text/html")
	url1 := router.NamedRoutes["hello"].URL("salutation", "hello", "name", "world")
	url2 := router.NamedRoutes["datastore-session"].URL()
	url3 := router.NamedRoutes["memcache-session"].URL()
	fmt.Fprintf(w, "Try a <a href='%s'>hello</a>. Or a <a href='%s'>datastore</a> or <a href='%s'>memcache</a> session.", url1, url2, url3)
}
Пример #3
0
func handle(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	item, err := memcache.Get(c, r.URL.Path)
	if err != nil && err != memcache.ErrCacheMiss {
		serveError(c, w, err)
		return
	}
	n := 0
	if err == nil {
		n, err = strconv.Atoi(string(item.Value))
		if err != nil {
			serveError(c, w, err)
			return
		}
	}
	n++
	item = &memcache.Item{
		Key:   r.URL.Path,
		Value: []byte(strconv.Itoa(n)),
	}
	err = memcache.Set(c, item)
	if err != nil {
		serveError(c, w, err)
		return
	}

	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "%q has been visited %d times", r.URL.Path, n)
}
Пример #4
0
func handle(w http.ResponseWriter, r *http.Request) {
	params, err := url.ParseQuery(r.URL.RawQuery)
	check(err)
	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add(
		"Access-Control-Allow-Methods",
		"OPTIONS, HEAD, GET, POST, PUT, DELETE",
	)
	switch r.Method {
	case "OPTIONS":
	case "HEAD":
	case "GET":
		get(w, r)
	case "POST":
		if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" {
			delete(w, r)
		} else {
			post(w, r)
		}
	case "DELETE":
		delete(w, r)
	default:
		http.Error(w, "501 Not Implemented", http.StatusNotImplemented)
	}
}
Пример #5
0
func (v *tplView) handle(w http.ResponseWriter, req *http.Request, s *session) {
	if v.checkUniqueURL != "" && req.URL.Path != v.checkUniqueURL {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "<pre>404 page not found</pre>")
		return
	}

	defer func() {
		if e := recover(); e != nil {
			fmt.Fprintf(w, "%v", e)
			log.Printf("Error in handling %v : %v", req.RawURL, e)
		}
	}()
	d := v.getData(req, s)
	// fmt.Printf("%#v\n", d) // DEBUG

	if ee, ok := d.(getDataError); ok {
		w.WriteHeader(ee.Code)
		e := tpl["error"].Execute(w, giveTplData{"Sess": s, "Error": ee, "Request": req})
		if e != nil {
			w.Write([]byte(e.String()))
		}
	} else if rurl, ok := d.(redirectResponse); ok {
		w.Header().Add("Location", string(rurl))
		w.WriteHeader(http.StatusFound)
	} else {
		e := tpl[v.tpl].Execute(w, giveTplData{"Sess": s, "Data": d, "Request": req})
		if e != nil {
			w.Write([]byte(e.String()))
		}
	}
}
Пример #6
0
// hello world, the web server
func PageExecuteJS(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	js := req.FormValue("js")
	header := w.Header()
	if url == "" {
		log.Printf("ERROR: url is required. (%s)\n", url)
		w.WriteHeader(http.StatusInternalServerError)
		header.Set("Content-Type", "text/plian;charset=UTF-8;")
		io.WriteString(w, "Internal Server Error: please input url.\n")
		return
	}
	if strings.Index(url, "http") != 0 {
		log.Printf("ERROR: url is invalid. (%s)\n", url)
		w.WriteHeader(http.StatusInternalServerError)
		header.Set("Content-Type", "text/plian;charset=UTF-8;")
		io.WriteString(w, "Internal Server Error: please input valid url.\n")
		return
	}
	if js == "" {
		log.Printf("ERROR: js is required. (%s)\n", url)
		w.WriteHeader(http.StatusInternalServerError)
		header.Set("Content-Type", "text/plian;charset=UTF-8;")
		io.WriteString(w, "Internal Server Error: please input js.\n")
		return
	}

	json := ExecuteJS(url, js)
	if len(json) == 0 {
		log.Printf("ERROR: failed to execute. (%s)\n", url)
		json = []byte("{}")
	}
	header.Set("Content-Type", "application/json;charset=UTF-8;")
	w.Write(json)
}
Пример #7
0
func ReturnJson(conn http.ResponseWriter, data interface{}) {
	conn.Header().Set("Content-Type", "text/javascript")

	if m, ok := data.(map[string]interface{}); ok {
		statusCode := 0
		if t, ok := m["error"].(string); ok && len(t) > 0 {
			statusCode = http.StatusInternalServerError
		}
		if t, ok := m["errorType"].(string); ok {
			switch t {
			case "server":
				statusCode = http.StatusInternalServerError
			case "input":
				statusCode = http.StatusBadRequest
			}
		}
		if statusCode != 0 {
			conn.WriteHeader(statusCode)
		}
	}

	bytes, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		BadRequestError(conn, fmt.Sprintf(
			"JSON serialization error: %v", err))
		return
	}
	conn.Write(bytes)
	conn.Write([]byte("\n"))
}
Пример #8
0
func solutionsHandler(w http.ResponseWriter, r *http.Request) {

	hint := r.FormValue("hint")
	if hint == "" {
		w.WriteHeader(http.StatusInternalServerError)
		w.Header().Set("Content-Type", "text/plain;charset=UTF-8;")
		io.WriteString(w, "Required parameter 'hint' not received.\n")
		return
	}

	// Use a regexp to find all actual characters
	// we already know about
	realCharExp := regexp.MustCompile("[^*]")
	realChars := realCharExp.FindAllString(hint, -1)

	// Replace all '_' in the hint expression for
	// 'any character that's not currently known'
	newr_str := strings.Replace(hint, "*",
		fmt.Sprintf("[^%s]", strings.Join(realChars, "")), -1)
	finalExp := regexp.MustCompile(fmt.Sprintf("^%s$", newr_str))

	io.WriteString(w, fmt.Sprintf(`<html>
<head><title>Possible Solutions for %s</title></head>
<body><h1>Possible Solutions for %s</h1><ul>`, hint, hint))
	// Now go through the word list looking for matches
	for i := range wordList.Words() {
		if finalExp.MatchString(wordList.Word(i)) {
			io.WriteString(w, fmt.Sprintf("<li>%s</li>", wordList.Word(i)))
		}
	}
	io.WriteString(w, "</ul></body></html>")

}
Пример #9
0
func handle_http(responseWrite http.ResponseWriter, request *http.Request) {
	var proxyResponse *http.Response
	var proxyResponseError os.Error

	proxyHost := strings.Split(request.URL.Path[6:], "/")[0]

	fmt.Printf("%s %s %s\n", request.Method, request.RawURL, request.RemoteAddr)
	//TODO https
	url := "http://" + request.URL.Path[6:]
	proxyRequest, _ := http.NewRequest(request.Method, url, nil)
	proxy := &http.Client{}
	proxyResponse, proxyResponseError = proxy.Do(proxyRequest)
	if proxyResponseError != nil {
		http.NotFound(responseWrite, request)
		return
	}
	for header := range proxyResponse.Header {
		responseWrite.Header().Add(header, proxyResponse.Header.Get(header))
	}
	contentType := strings.Split(proxyResponse.Header.Get("Content-Type"), ";")[0]
	if proxyResponseError != nil {
		fmt.Fprintf(responseWrite, "pizda\n")
	} else if ReplacemendContentType[contentType] {
		body, _ := ioutil.ReadAll(proxyResponse.Body)
		defer proxyResponse.Body.Close()
		bodyString := replace_url(string(body), "/http/", proxyHost)

		responseWrite.Write([]byte(bodyString))

	} else {
		io.Copy(responseWrite, proxyResponse.Body)
	}
}
Пример #10
0
func printSpamHamJSON(w http.ResponseWriter, r *http.Request, key string) {
	c := appengine.NewContext(r)

	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	q := datastore.NewQuery(key)
	fmt.Fprintf(w, "[")
	first := true
	for t := q.Run(c); ; {
		var x Entity
		_, err := t.Next(&x)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return
		}
		if !first {
			fmt.Fprintf(w, ", %s", x.Value)
		} else {
			fmt.Fprintf(w, "%s", x.Value)
			first = false
		}
	}
	fmt.Fprintf(w, "]")
}
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
	}

}
Пример #12
0
// hello world, the web server
func Capture(w http.ResponseWriter, req *http.Request) {
	url := req.FormValue("url")
	header := w.Header()
	if url == "" {
		log.Printf("ERROR: url is required. (%s)\n", url)
		w.WriteHeader(http.StatusInternalServerError)
		header.Set("Content-Type", "text/plian;charset=UTF-8;")
		io.WriteString(w, "Internal Server Error: please input url.\n")
		return
	}
	if strings.Index(url, "http") != 0 {
		log.Printf("ERROR: url is invalid. (%s)\n", url)
		w.WriteHeader(http.StatusInternalServerError)
		header.Set("Content-Type", "text/plian;charset=UTF-8;")
		io.WriteString(w, "Internal Server Error: please input valid url.\n")
		return
	}
	image := CaptureUrl(url)
	if len(image) == 0 {
		log.Printf("ERROR: failed to capture. (%s)\n", url)
		w.WriteHeader(http.StatusInternalServerError)
		header.Set("Content-Type", "text/plian;charset=UTF-8;")
		io.WriteString(w, "Internal Server Error: Failed to capture.\n")
		return
	}
	header.Set("Content-Type", "image/png")
	w.Write(image)
}
Пример #13
0
func handleGet(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(405)
	fmt.Fprintf(w, "405 Method Not Allowed\n\n"+
		"To access this amf.go gateway you must use POST requests "+
		"(%s received))")
}
Пример #14
0
func (h *TestHandler) ServeHTTP(w http.ResponseWriter, hr *http.Request) {
	h.hit()
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Request-Method", "GET")

	fmt.Println("\n=== TestHandler : Requete reçue ====================")
	fmt.Println(" Method : " + hr.Method)
	fmt.Println(" URL : " + hr.RawURL)
	fmt.Println(" Proto : " + hr.Proto)
	fmt.Printf(" ContentLength : %d\n", hr.ContentLength)
	fmt.Println(" UserAgent : " + hr.UserAgent)
	fmt.Println(" Header :")
	for key, value := range hr.Header {
		fmt.Printf("  %s=%v\n", key, value)
	}

	b, e := ioutil.ReadAll(hr.Body)
	if e != nil {
		fmt.Println("Erreur lecture :")
		fmt.Println(e)
	}
	s := string(b)
	fmt.Print(s)

	fmt.Fprint(w, "Bien reçu")
}
Пример #15
0
func uploadUser(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		// No upload; show the upload form.
		uploadUserTemplate.Execute(w, nil)
		return
	}

	f, _, err := r.FormFile("image")
	errors.Check(err)
	defer f.Close()

	// Grab the image data
	i, _, err := image.Decode(f)
	errors.Check(err)

	var key string = keyOf()

	// store image
	i = picstore.Store(key, i, 320, "userimg")
	i = picstore.Store(key, i, 180, "userthumb")
	// generate result

	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("cache-control", "no-cache")
	w.Header().Set("Expires", "-1")
	fmt.Fprintf(w, "{\"profilePicUrl\":\"uimg?id="+key+"\",\"profileThumbUrl\":\"utmb?id="+key+"\"}")
}
Пример #16
0
func GCServer(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	StatsServer(w, req)
	io.WriteString(w, "=============================\n")
	runtime.GC()
	StatsServer(w, req)
}
Пример #17
0
// Symbol looks up the program counters listed in the request,
// responding with a table mapping program counters to function names.
// The package initialization registers it as /debug/pprof/symbol.
func Symbol(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	// We don't know how many symbols we have, but we
	// do have symbol information.  Pprof only cares whether
	// this number is 0 (no symbols available) or > 0.
	fmt.Fprintf(w, "num_symbols: 1\n")

	var b *bufio.Reader
	if r.Method == "POST" {
		b = bufio.NewReader(r.Body)
	} else {
		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
	}

	for {
		word, err := b.ReadSlice('+')
		if err == nil {
			word = word[0 : len(word)-1] // trim +
		}
		pc, _ := strconv.Btoui64(string(word), 0)
		if pc != 0 {
			f := runtime.FuncForPC(uintptr(pc))
			if f != nil {
				fmt.Fprintf(w, "%#x %s\n", pc, f.Name())
			}
		}

		// Wait until here to check for err; the last
		// symbol will have an err because it doesn't end in +.
		if err != nil {
			break
		}
	}
}
Пример #18
0
func (ui *UIHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	base := req.Header.Get("X-PrefixHandler-PathBase")
	suffix := req.Header.Get("X-PrefixHandler-PathSuffix")

	rw.Header().Set("Vary", "Accept")
	switch {
	case wantsDiscovery(req):
		ui.serveDiscovery(rw, req)
	case wantsUploadHelper(req):
		ui.serveUploadHelper(rw, req)
	case strings.HasPrefix(suffix, "download/"):
		ui.serveDownload(rw, req)
	case strings.HasPrefix(suffix, "thumbnail/"):
		ui.serveThumbnail(rw, req)
	default:
		file := ""
		if m := staticFilePattern.FindStringSubmatch(suffix); m != nil {
			file = m[1]
		} else {
			switch {
			case wantsPermanode(req):
				file = "permanode.html"
			case wantsBlobInfo(req):
				file = "blobinfo.html"
			case req.URL.Path == base:
				file = "index.html"
			default:
				http.Error(rw, "Illegal URL.", 404)
				return
			}
		}
		vfs.ServeFileFromFS(rw, req, uiFiles, file)
	}
}
Пример #19
0
func PageInternalUpdateJson(w http.ResponseWriter, req *http.Request) {
	id := req.FormValue("id")
	updateJson := req.FormValue("json")
	header := w.Header()
	conn, err := GetConnection()
	c := GetExecuteCollection(conn)
	var (
		rs    ExecuteRs
		jsonb []byte
	)
	execId, err := mongo.NewObjectIdHex(id)
	log.Printf("Search ExecuteId=%s", execId)
	err = c.Find(map[string]interface{}{"_id": execId}).One(&rs)
	if err != nil {
		jsonb = []byte(`{error: "Not found."}`)
	} else {
		rs.Json = updateJson
		err = c.Update(mongo.M{"_id": execId}, rs)
		if err != nil {
			jsonb = []byte(`{result: "failed"}`)
		} else {
			jsonb = []byte(`{result: "success"}`)
		}
	}

	conn.Close()

	header.Set("Access-Control-Allow-Origin", "*")
	header.Set("Content-Type", "application/json")
	w.Write(jsonb)
}
Пример #20
0
func (ui *UIHandler) serveDiscovery(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Set("Content-Type", "text/javascript")
	inCb := false
	if cb := req.FormValue("cb"); identPattern.MatchString(cb) {
		fmt.Fprintf(rw, "%s(", cb)
		inCb = true
	}

	pubRoots := map[string]interface{}{}
	for key, pubh := range ui.PublishRoots {
		pubRoots[key] = map[string]interface{}{
			"name": pubh.RootName,
			// TODO: include gpg key id
		}
	}

	bytes, _ := json.Marshal(map[string]interface{}{
		"blobRoot":       ui.BlobRoot,
		"searchRoot":     ui.SearchRoot,
		"jsonSignRoot":   ui.JSONSignRoot,
		"uploadHelper":   "?camli.mode=uploadhelper", // hack; remove with better javascript
		"downloadHelper": "./download/",
		"publishRoots":   pubRoots,
	})
	rw.Write(bytes)
	if inCb {
		rw.Write([]byte{')'})
	}
}
Пример #21
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)
}
Пример #22
0
func handleCreate(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		return
	}

	r.ParseForm()
	url := r.FormValue("url")
	title := r.FormValue("title")
	tagString := r.FormValue("tags")
	if url == "" {
		output(c, w, "create")
		return
	}

	tags := strings.Split(tagString, ",")
	bm := bookmarks.NewBookmark(u, url, title, tags)
	_, err := bm.Save(c)
	if err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Location", rootURL(c))
	w.WriteHeader(http.StatusFound)
	return
}
Пример #23
0
func ServeDataItemPage(writer http.ResponseWriter, request *http.Request) {
	if strings.Contains(request.Header.Get("Accept"), "application/json") {
		writer.Header().Set("Content-Type", "applicaton/json")
	} else {
		writer.Header().Set("Content-Type", "text/plain")
	}

	stream := StreamByName("ranger")

	log.Printf("Serving full data for '%s'", request.FormValue("q"))
	data := stream.LookupData(request.FormValue("q"))
	if data == nil {
		log.Printf("Failed to find %s", request.FormValue("q"))
		writer.WriteHeader(http.StatusNotFound)
		return
	}

	outputBytes, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		log.Printf("Failed to format data")
		writer.WriteHeader(http.StatusInternalServerError)
		return
	}

	writer.Write(outputBytes)
}
Пример #24
0
// exec a program, redirecting output
func DateServer(rw http.ResponseWriter, req *http.Request) {
	rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
	r, w, err := os.Pipe()
	if err != nil {
		fmt.Fprintf(rw, "pipe: %s\n", err)
		return
	}

	p, err := os.StartProcess("/bin/date", []string{"date"}, &os.ProcAttr{Files: []*os.File{nil, w, w}})
	defer r.Close()
	w.Close()
	if err != nil {
		fmt.Fprintf(rw, "fork/exec: %s\n", err)
		return
	}
	defer p.Release()
	io.Copy(rw, r)
	wait, err := p.Wait(0)
	if err != nil {
		fmt.Fprintf(rw, "wait: %s\n", err)
		return
	}
	if !wait.Exited() || wait.ExitStatus() != 0 {
		fmt.Fprintf(rw, "date: %v\n", wait)
		return
	}
}
Пример #25
0
func (v *redirectView) handle(w http.ResponseWriter, req *http.Request, s *session) {
	if v.checkUniqueURL != "" && req.URL.Path != v.checkUniqueURL {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "<pre>404 page not found</pre>")
		return
	}

	defer func() {
		if e := recover(); e != nil {
			fmt.Fprintf(w, "%v", e)
			log.Printf("Error in handling %v : %v", req.RawURL, e)
			gde, ok := e.(getDataError)
			if !ok {
				if ose, ok := e.(os.Error); ok {
					gde = getDataError{http.StatusInternalServerError, ose}
				} else {
					gde = getDataError{http.StatusInternalServerError, os.NewError(fmt.Sprintf("%v", e))}
				}
			}
			w.WriteHeader(gde.Code)
			e2 := tpl["error"].Execute(w, giveTplData{"Sess": s, "Error": gde, "Request": req})
			if e2 != nil {
				w.Write([]byte(e2.String()))
			}
		}
	}()

	rurl := v.process(req, s)
	if rurl == "" {
		rurl = "/"
	}
	w.Header().Add("Location", rurl)
	w.WriteHeader(http.StatusFound)
}
Пример #26
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)
}
Пример #27
0
func (session *Session) SetCookie(w http.ResponseWriter, context appengine.Context) {
	cookie := &http.Cookie{
		Name:  "session",
		Value: session.Key,
	}
	w.Header().Add("Set-Cookie", cookie.String())
}
Пример #28
0
func serveObject(val reflect.Value, w http.ResponseWriter, r *http.Request) os.Error {
	switch r.Method {
	case "HEAD", "GET", "PUT":
	default:
		return nil
		return &BadMethod{r.URL.Path, r.Method, val.Interface()}
	}

	ctype := "application/json"
	// TODO(kevlar): Content type negotiation
	w.Header().Set("Content-Type", ctype)

	if r.Method == "HEAD" {
		return nil
	}

	js, err := json.Marshal(val.Interface())
	if err != nil {
		return &FailedEncode{err, ctype, val.Interface()}
	}

	if _, err := w.Write(js); err != nil {
		return err
	}

	return nil
}
Пример #29
0
// tileHandler implements a tile renderer for use with the Google Maps JavaScript API.
// See http://code.google.com/apis/maps/documentation/javascript/maptypes.html#ImageMapTypes
func tileHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	x, _ := strconv.Atoi(r.FormValue("x"))
	y, _ := strconv.Atoi(r.FormValue("y"))
	z, _ := strconv.Atoi(r.FormValue("z"))

	w.Header().Set("Content-Type", "image/png")

	// Try memcache first.
	key := fmt.Sprintf("mandelbrot:%d/%d/%d", x, y, z)
	if z < maxMemcacheLevel {
		if item, err := memcache.Get(c, key); err == nil {
			w.Write(item.Value)
			return
		}
	}

	b := render(x, y, z)
	if z < maxMemcacheLevel {
		memcache.Set(c, &memcache.Item{
			Key:        key,
			Value:      b,
			Expiration: 3600, // TTL = 1 hour
		})
	}

	w.Header().Set("Content-Length", strconv.Itoa(len(b)))
	w.Write(b)
}
Пример #30
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)
}