Esempio n. 1
0
// GetApiConfigs creates APIDescriptor for every registered RPCService and
// responds with a config suitable for generating Discovery doc.
//
// Responds with a list of active APIs and their configuration files.
func (s *BackendService) GetApiConfigs(
	r *http.Request, req *GetAPIConfigsRequest, resp *APIConfigsList) error {
	c := appengine.NewContext(r)
	if req.AppRevision != "" {
		revision := strings.Split(appengine.VersionID(c), ".")[1]
		if req.AppRevision != revision {
			err := fmt.Errorf(
				"API backend app revision %s not the same as expected %s",
				revision, req.AppRevision)
			c.Errorf("%s", err)
			return err
		}
	}

	resp.Items = make([]string, 0)
	for _, service := range s.server.services.services {
		if service.internal {
			continue
		}
		d := &APIDescriptor{}
		if err := service.APIDescriptor(d, r.Host); err != nil {
			c.Errorf("%s", err)
			return err
		}
		bytes, err := json.Marshal(d)
		if err != nil {
			c.Errorf("%s", err)
			return err
		}
		resp.Items = append(resp.Items, string(bytes))
	}
	return nil
}
Esempio n. 2
0
func aboutPage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	fmt.Fprintf(w, "<h1>%v</h1>", appengine.DefaultVersionHostname(c))

	token, expire, _ := appengine.AccessToken(c, "test")
	fmt.Fprintf(w, "<p>AccessToken: %v %v", token, expire)

	fmt.Fprintf(w, "<p>AppID: %v", appengine.AppID(c))
	fmt.Fprintf(w, "<p>FQAppID: %v", c.FullyQualifiedAppID())
	fmt.Fprintf(w, "<p>Go version: %v", runtime.Version())
	fmt.Fprintf(w, "<p>Datacenter: %v", appengine.Datacenter())
	fmt.Fprintf(w, "<p>InstanceID: %v", appengine.InstanceID())
	fmt.Fprintf(w, "<p>IsDevAppServer: %v", appengine.IsDevAppServer())
	fmt.Fprintf(w, "<p>RequestID: %v", appengine.RequestID(c))
	fmt.Fprintf(w, "<p>ServerSoftware: %v", appengine.ServerSoftware())

	sa, _ := appengine.ServiceAccount(c)
	fmt.Fprintf(w, "<p>ServiceAccount: %v", sa)

	keyname, signed, _ := appengine.SignBytes(c, []byte("test"))
	fmt.Fprintf(w, "<p>SignBytes: %v %v", keyname, signed)
	fmt.Fprintf(w, "<p>VersionID: %v", appengine.VersionID(c))

	fmt.Fprintf(w, "<p>Request: %v", r)
	r2 := c.Request()
	fmt.Fprintf(w, "<p>Context Request type/value: %T %v", r2, r2)
}
Esempio n. 3
0
func root(rw http.ResponseWriter, r *http.Request) {
	context := appengine.NewContext(r)
	version, _ := strconv.ParseInt(strings.Split(appengine.VersionID(context), ".")[1], 10, 64)
	ctime := time.Unix(version/(1<<28)+8*3600, 0).Format(time.RFC3339)
	rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
	fmt.Fprintf(rw, "GoProxy server %s works, deployed at %s\n", Version, ctime)
}
Esempio n. 4
0
// Run starts a query for log records, which contain request and application
// level log information.
func (params *Query) Run(c appengine.Context) *Result {
	req := &log_proto.LogReadRequest{}
	appId := c.FullyQualifiedAppID()
	req.AppId = &appId
	if params.StartTime != 0 {
		req.StartTime = &params.StartTime
	}
	if params.EndTime != 0 {
		req.EndTime = &params.EndTime
	}
	if params.Incomplete {
		req.IncludeIncomplete = &params.Incomplete
	}
	if params.AppLogs {
		req.IncludeAppLogs = &params.AppLogs
	}
	if params.ApplyMinLevel {
		req.MinimumLogLevel = proto.Int32(int32(params.MinLevel))
	}
	if params.Versions == nil {
		// If no versions were specified, default to the major version
		// used by this app.
		versionID := appengine.VersionID(c)
		if i := strings.Index(versionID, "."); i >= 0 {
			versionID = versionID[:i]
		}
		req.VersionId = []string{versionID}
	} else {
		req.VersionId = params.Versions
	}

	return &Result{context: c, request: req}
}
Esempio n. 5
0
// HTTP handler for /feed
func feedHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-control", config.Require("cache_control_header"))

	c := appengine.NewContext(r)
	key := r.URL.Path + "@" + appengine.VersionID(c)

	if item, err := memcache.Get(c, key); err == memcache.ErrCacheMiss {
		c.Infof("Page %s not in the cache", key)
	} else if err != nil {
		c.Errorf("error getting page: %v", err)
	} else {
		c.Infof("Page %s found in the cache", key)
		w.Write(item.Value)
		return
	}

	entry_count, _ := config.GetInt("entries_per_page")
	entries, _ := GetEntries(c, EntryQuery{IsPage: false, Count: int(entry_count)})
	links := make([]SavedLink, 0)

	context, _ := GetTemplateContext(entries, links, "Atom Feed", "feed", r)
	var contentBuffer bytes.Buffer
	feedTpl.ExecuteTemplate(&contentBuffer, "feed.html", context)
	content, _ := ioutil.ReadAll(&contentBuffer)

	w.Write(content)
	// Feeds get cached infinitely, until an edit flushes it.
	storeInCache(c, key, content, 0)
}
Esempio n. 6
0
// Run starts a query for log records, which contain request and application
// level log information.
func (params *Query) Run(c appengine.Context) *Result {
	req, err := makeRequest(params, c.FullyQualifiedAppID(), appengine.VersionID(c))
	return &Result{
		context: c,
		request: req,
		err:     err,
	}
}
Esempio n. 7
0
func (h Handler) get() {
	version, _ := strconv.ParseInt(strings.Split(appengine.VersionID(h.context), ".")[1], 10, 64)
	ctime := time.Unix(version/(1<<28)+8*3600, 0).Format(time.RFC3339)

	h.response.WriteHeader(http.StatusOK)
	h.response.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(h.response, "GoAgent Go Server %s \xe5\xb7\xb2\xe7\xbb\x8f\xe5\x9c\xa8\xe5\xb7\xa5\xe4\xbd\x9c\xe4\xba\x86\xef\xbc\x8c\xe9\x83\xa8\xe7\xbd\xb2\xe6\x97\xb6\xe9\x97\xb4 %s\n", Version, ctime)
}
Esempio n. 8
0
// handler is the main demo entry point that calls the GCS operations.
func handler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	c := appengine.NewContext(r)
	if bucket == "" {
		var err error
		if bucket, err = file.DefaultBucketName(c); err != nil {
			c.Errorf("failed to get default GCS bucket name: %v", err)
			return
		}
	}
	hc := &http.Client{
		Transport: &oauth2.Transport{
			Source: google.AppEngineTokenSource(c, storage.ScopeFullControl),
			Base:   &urlfetch.Transport{Context: c},
		},
	}
	ctx := cloud.NewContext(appengine.AppID(c), hc)
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	fmt.Fprintf(w, "Demo GCS Application running from Version: %v\n", appengine.VersionID(c))
	fmt.Fprintf(w, "Using bucket name: %v\n\n", bucket)

	d := &demo{
		c:   c,
		w:   w,
		ctx: ctx,
	}

	n := "demo-testfile-go"
	d.createFile(n)
	d.readFile(n)
	d.copyFile(n)
	d.statFile(n)
	d.createListFiles()
	d.listBucket()
	d.listBucketDirMode()
	d.defaultACL()
	d.putDefaultACLRule()
	d.deleteDefaultACLRule()
	d.bucketACL()
	d.putBucketACLRule()
	d.deleteBucketACLRule()
	d.acl(n)
	d.putACLRule(n)
	d.deleteACLRule(n)
	d.deleteFiles()

	if d.failed {
		io.WriteString(w, "\nDemo failed.\n")
	} else {
		io.WriteString(w, "\nDemo succeeded.\n")
	}
}
Esempio n. 9
0
func BranchName(c appengine.Context) string {
	if appengine.IsDevAppServer() {
		return "localhost"
	}

	branchName := strings.Split(appengine.VersionID(c), ".")[0]
	if len(branchName) > 0 {
		return branchName
	}
	return "unkown"
}
Esempio n. 10
0
func handler(f func(c common.Context)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := common.Context{
			Context: appengine.NewContext(r),
			Req:     r,
			Resp:    w,
			Vars:    mux.Vars(r),
		}
		c.User = user.Current(c)
		c.Version = appengine.VersionID(c.Context)
		f(c)
	}
}
Esempio n. 11
0
//  info generates a page of information useful to the developers
func info(w http.ResponseWriter, r *http.Request) {

	// must do all reading before any writing
	var data struct {
		Req    *http.Request
		Body   []byte
		BE     error
		Dctr   string
		GoArch string
		GoOs   string
		GoVer  string
		VID    string
		Vtime  string
		MaxCx  int
	}
	data.Req = r
	data.Body, data.BE = ioutil.ReadAll(r.Body)
	data.Dctr = appengine.Datacenter()
	data.GoArch = runtime.GOARCH
	data.GoOs = runtime.GOOS
	data.GoVer = runtime.Version()
	data.VID = appengine.VersionID(appengine.NewContext(r))
	data.MaxCx = rx.MaxComplexity

	var ver int
	var bigtime int64
	fmt.Sscanf(data.VID, "%d.%d", &ver, &bigtime)
	if strings.HasPrefix(r.Host, "localhost:") {
		// don't know how to decode this in SDK environment
		data.Vtime = "?!"
	} else {
		// decode VID to match with appengine admin logs
		t := time.Unix(bigtime>>28, 0)
		data.Vtime = t.Format("01/02 15:04")
	}

	putheader(w, r, "Info")

	fmt.Fprint(w,
		"<P>(Information for use of the website maintainers.)\n<P>")
	fmt.Fprintf(w, "<span class=cg>= cg =</span>&nbsp;\n") // .cg
	fmt.Fprintf(w, "<span class=cw>= cw =</span>&nbsp;\n") // .cw
	for i := 0; i < NCOLORS; i++ {
		fmt.Fprintf(w, "<span class=%s>= %s =</span>&nbsp;\n",
			colorname(i), colorname(i))
	}
	fmt.Fprintln(w)
	tInfo.Execute(w, data)
	putfooter(w, r)
}
Esempio n. 12
0
File: id.go Progetto: LeXa4894/test
func handleID(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	fmt.Fprintf(w, "appengine.AppID(c) = %q\n", appengine.AppID(c))
	fmt.Fprintf(w, "appengine.VersionID(c) = %q\n", appengine.VersionID(c))

	name, index := appengine.BackendInstance(c)
	fmt.Fprintf(w, "appengine.BackendInstance(c) = %q, %d\n", name, index)

	fmt.Fprintf(w, "----------\n")
	for _, s := range os.Environ() {
		fmt.Fprintln(w, s)
	}
}
Esempio n. 13
0
// Run starts a query for log records, which contain request and application
// level log information.
func (params *Query) Run(c appengine.Context) *Result {
	req := &pb.LogReadRequest{}
	appId := c.FullyQualifiedAppID()
	req.AppId = &appId
	if !params.StartTime.IsZero() {
		req.StartTime = proto.Int64(params.StartTime.UnixNano() / 1e3)
	}
	if !params.EndTime.IsZero() {
		req.EndTime = proto.Int64(params.EndTime.UnixNano() / 1e3)
	}
	if params.Offset != nil {
		var offset pb.LogOffset
		if err := proto.Unmarshal(params.Offset, &offset); err != nil {
			return &Result{context: c, err: fmt.Errorf("bad Offset: %v", err)}
		}
		req.Offset = &offset
	}
	if params.Incomplete {
		req.IncludeIncomplete = &params.Incomplete
	}
	if params.AppLogs {
		req.IncludeAppLogs = &params.AppLogs
	}
	if params.ApplyMinLevel {
		req.MinimumLogLevel = proto.Int32(int32(params.MinLevel))
	}
	if params.Versions == nil {
		// If no versions were specified, default to the major version
		// used by this app.
		versionID := appengine.VersionID(c)
		if i := strings.Index(versionID, "."); i >= 0 {
			versionID = versionID[:i]
		}
		req.VersionId = []string{versionID}
	} else {
		req.VersionId = params.Versions
	}
	if params.RequestIDs != nil {
		ids := make([][]byte, len(params.RequestIDs))
		for i, v := range params.RequestIDs {
			ids[i] = []byte(v)
		}
		req.RequestId = ids
	}

	return &Result{context: c, request: req}
}
Esempio n. 14
0
func handleID(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")

	fmt.Fprintf(w, "appengine.AppID(c) = %q\n", appengine.AppID(c))
	fmt.Fprintf(w, "appengine.VersionID(c) = %q\n", appengine.VersionID(c))

	name := appengine.ModuleName(c)
	hostname, err := appengine.ModuleHostname(c, "", "", "")
	fmt.Fprintf(w, "appengine.ModuleName(c) = %q\n", name)
	fmt.Fprintf(w, `appengine.ModuleHostname(c, "", "", "") = %q (err: %v)`+"\n", hostname, err)

	fmt.Fprintf(w, "----------\n")
	for _, s := range os.Environ() {
		fmt.Fprintln(w, s)
	}
}
Esempio n. 15
0
func AppCache(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	w.Header().Set("Content-Type", "text/cache-manifest")
	w.Header().Set("Cache-Control", "private, max-age=0, must-revalidate")

	// Data to be sent to the template:
	data := Template{Version: appengine.VersionID(c)}

	// Parse the template and output HTML:
	template, err := template.ParseFiles("support/manifest.appcache.skel")
	if err != nil {
		c.Criticalf("execution failed: %s", err)
	}
	err = template.Execute(w, data)
	if err != nil {
		c.Criticalf("execution failed: %s", err)
	}
}
Esempio n. 16
0
func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, "<!DOCTYPE html>")
	fmt.Fprintf(w, "<html><head><title>appengineパッケージ</title></head><body>")

	if appengine.IsDevAppServer() {
		// 開発環境
		fmt.Fprintf(w, "開発環境で動作しています。。<br>")
	} else {
		fmt.Fprintf(w, "本番環境で動作しています。<br>")
	}

	c := appengine.NewContext(r)

	fmt.Fprintf(w, "AppID(): %s<br>", appengine.AppID(c))
	fmt.Fprintf(w, "DefaultVersionHostname(): %s<br>", appengine.DefaultVersionHostname(c))

	fmt.Fprintf(w, "VersionID(): %s<br>", appengine.VersionID(c))
	fmt.Fprintf(w, "</body></html>")
}
Esempio n. 17
0
func Main(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	h := w.Header()
	h.Set("Content-Type", "text/html; charset=utf-8")
	h.Set("Cache-Control", "private, max-age=0, must-revalidate")

	c.Debugf("Headers: %v", r.Header)

	// redirect to room name
	if r.URL.Path == "/" && !SkipRedirect(r) {
		roomName := Random(6)
		path := "/"

		// room doesn't exists, redirect to it
		// (or we'll just redirect back to "/")
		if _, err := GetRoom(c, roomName); err != nil {
			path = "/" + roomName
		} else {
			c.Debugf("Room already exist. Generating a random string instead.")
			path = "/" + Random(6)
		}
		if r.URL.RawQuery != "" {
			path = path + "?" + r.URL.RawQuery
		}
		http.Redirect(w, r, path, 302)
		return
	}

	q := r.URL.Query()
	appchan := q.Get("signal") != "ws"

	// clean up the roomName to avoid xss
	roomName := Cleanup(strings.TrimLeft(r.URL.Path, "/"))

	// to make sure that players have the same settings
	// in multiplayer we include the query in the room name
	if r.URL.RawQuery != "" {
		roomName = roomName + "-" + r.URL.RawQuery
	}

	// Data to be sent to the template:
	data := Template{Room: roomName, AcceptLanguage: AcceptLanguage(r), Minified: Minified(), Dev: appengine.IsDevAppServer(), Version: appengine.VersionID(c)}

	// skip rooms when using WebSocket signals
	// or when room name is empty
	if roomName == "" {
		c.Debugf("Room with no name.")
		data.State = "room-empty"

	} else if appchan {
		room, err := GetRoom(c, roomName)

		// Empty room
		if room == nil {
			room = new(Room)
			c.Debugf("Created room %s", roomName)
			if err := PutRoom(c, roomName, room); err != nil {
				c.Criticalf("Error occured while creating room %s: %+v", roomName, err)
				return
			}
			data.State = "room-empty"

			// Lonely room
		} else if room.Occupants() == 1 {
			data.State = "room-lonely"

			// Full room
		} else if room.Occupants() == 2 {
			data.State = "room-full"

			// DataStore error
		} else if err != nil {
			c.Criticalf("Error occured while getting room %s: %+v", roomName, err)
			return
		}
	}

	// Parse the template and output HTML:
	template, err := template.ParseFiles("build/build.html")
	if err != nil {
		c.Criticalf("execution failed: %s", err)
	}
	err = template.Execute(w, data)
	if err != nil {
		c.Criticalf("execution failed: %s", err)
	}
}
Esempio n. 18
0
func handleUploadImage(c appengine.Context, w http.ResponseWriter, r *http.Request) {
	file, fileHeader, err := r.FormFile(uploadImageKey)
	if err != nil {
		c.Infof("Failed to get uploaded image: %v", err)
		http.Error(w, "Failed to get uploaded image", http.StatusBadRequest)
		return
	}
	defer file.Close()
	data, err := ioutil.ReadAll(file)
	if err != nil {
		c.Errorf("Failed to read uploaded image: %v", err)
		http.Error(w, "Failed to get uploaded image", http.StatusBadRequest)
		return
	}
	ext := path.Ext(fileHeader.Filename)
	mimeType := mime.TypeByExtension(ext)

	// create context for Google Cloud Storage and upload file
	gc := gappengine.NewContext(r)
	hc := &http.Client{
		Transport: &oauth2.Transport{
			Source: google.AppEngineTokenSource(gc, storage.ScopeFullControl),
			Base:   &urlfetch.Transport{Context: gc},
		},
	}
	ctx := cloud.NewContext(gappengine.AppID(gc), hc)
	c.Infof("Demo GCS Application running from Version: %v\n", appengine.VersionID(c))

	filePath := path.Join(tempImagePath, createTempImagePath, fileHeader.Filename)
	c.Infof("file: %v, size: %d, MIME: %v, path: %v", fileHeader.Filename, len(data), mimeType, filePath)
	wc := storage.NewWriter(ctx, bucketName, filePath)
	wc.ContentType = mimeType
	_, err = wc.Write(data)
	if err != nil {
		c.Errorf("Failed to upload image: %v", err)
		http.Error(w, "Failed to upload image", http.StatusInternalServerError)
		return
	}
	err = wc.Close()
	if err != nil {
		c.Errorf("Failed to close uploaded image: %v", err)
		http.Error(w, "Failed to upload image", http.StatusInternalServerError)
		return
	}
	obj, err := storage.StatObject(ctx, bucketName, filePath)
	if err != nil {
		c.Errorf("Failed to stat object: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// c.Infof("obj: %v", obj)
	// get blob key for GCS file
	// obj := wc.Object()
	objName := path.Join("/gs", bucketName, obj.Name)
	c.Infof("Getting blob key from path: %v", objName)
	imgKey, err := blobstore.BlobKeyForFile(c, objName)
	if err != nil {
		c.Errorf("Failed to get image blob key: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	url, err := getImageUrl(c, imgKey)
	if err != nil {
		c.Errorf("Failed to get room image url: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	info := ImageInfo{
		Key: imgKey,
		Url: url.String(),
	}
	outBuf, err := json.Marshal(&info)
	if err != nil {
		c.Errorf("%s", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	_, err = w.Write(outBuf)
	if err != nil {
		c.Errorf("%s", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Esempio n. 19
0
// query implements a basic HTML form to examine logs and format the output
// using Go templates.
func query(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	// Create a log.Query object; by default we request application logs,
	// but leave everything else at its zero value.
	query := &log.Query{AppLogs: true}

	// Parse the URL parameters, handling absent or invalid values.
	version := r.FormValue("version")
	if len(version) != 0 {
		query.Versions = []string{version}
	} else {
		// Compute the current major version ID for the form.
		version = appengine.VersionID(c)
		if i := strings.Index(version, "."); i > -1 {
			version = version[:i]
		}
	}
	level, err := strconv.Atoi(r.FormValue("level"))
	if err == nil && level > -1 && level < len(appLevels) {
		query.ApplyMinLevel = true
		query.MinLevel = level
	} else {
		level = -1
	}
	count, err := strconv.Atoi(r.FormValue("count"))
	if err != nil {
		count = 25
	}
	offset, err := base64.URLEncoding.DecodeString(r.FormValue("offset"))
	if err == nil && len(offset) > 0 {
		query.Offset = offset
	}

	// Set up a map of untyped values to pass to the log template.  Our
	// interpretations of the URL parameters are here to populate the form.
	data := struct {
		AppLevels []appLevel
		Version   string
		Level     int
		Count     int
		Error     error
		Next      string
		Logs      []*log.Record
	}{
		AppLevels: appLevels, // We'll build the form from appLevels as well.
		Version:   version,
		Level:     level,
		Count:     count,
	}

	// Run the query and read at most count records.
	for results := query.Run(c); len(data.Logs) < count; {
		record, err := results.Next()
		if err != nil {
			if err != log.Done {
				c.Errorf("Failed to retrieve log: %v", err)
				data.Error = err
			}
			break
		}
		data.Logs = append(data.Logs, record)
	}
	if len(data.Logs) == count {
		v := r.URL.Query()
		offset := data.Logs[len(data.Logs)-1].Offset
		v.Set("offset", base64.URLEncoding.EncodeToString(offset))
		data.Next = v.Encode()
	}

	// Execute the main page template and return the response.
	if err := mainPageTmpl.ExecuteTemplate(w, "log.html", data); err != nil {
		c.Errorf("Failed to execute template: %v", err)
	}
}
Esempio n. 20
0
func VersionID(ctx netcontext.Context) string  { return appengine.VersionID(fromContext(ctx)) }
Esempio n. 21
0
// HTTP handler for rendering blog entries
func rootHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-control", config.Require("cache_control_header"))

	c := appengine.NewContext(r)
	key := r.URL.Path + "@" + appengine.VersionID(c)

	if item, err := memcache.Get(c, key); err == memcache.ErrCacheMiss {
		c.Infof("Page %s not in the cache", key)
	} else if err != nil {
		c.Errorf("error getting page: %v", err)
	} else {
		c.Infof("Page %s found in the cache", key)
		w.Write(item.Value)
		return
	}

	template := *errorTpl
	title := "Error"
	nextURL := ""
	previousURL := ""

	var entries []SavedEntry
	links, _ := GetLinks(c)
	path := r.URL.Path

	pageCount, _ := strconv.Atoi(filepath.Base(r.URL.Path))
	c.Infof("Page count: %d for %s", pageCount, r.URL.Path)
	if pageCount > 1 {
		path = filepath.Dir(path)
		if pageCount > 2 {
			previousURL = fmt.Sprintf("%s%d", path, pageCount-1)
		} else {
			// Don't link to /1, just link to the base path.
			previousURL = path
		}
	} else {
		pageCount = 1
	}

	if path == "/" {
		title = config.Require("subtitle")
		template = *archiveTpl
		entries_per_page, _ := config.GetInt("entries_per_page")
		offset := int(entries_per_page) * (pageCount - 1)
		c.Infof("Page %d - Entries Per page: %d - Offset: %d", pageCount, entries_per_page, offset)
		query := EntryQuery{
			IsPage: false,
			// We ask for 1 more than required so that we know if there are more links to show.
			Count:  int(entries_per_page) + 1,
			Offset: offset,
		}
		entries, _ = GetEntries(c, query)

		if len(entries) > int(entries_per_page) {
			nextURL = fmt.Sprintf("%s%d", path, pageCount+1)
			entries = entries[:entries_per_page]
		}

	} else {
		entry, err := GetSingleEntry(c, filepath.Base(r.URL.Path))
		if err != nil {
			http.Error(w, "I looked for an entry, but it was not there.", http.StatusNotFound)
			return
		} else {
			title = entry.Title
			entries = append(entries, entry)
			if entry.IsPage == true {
				template = *pageTpl
			} else {
				template = *entryTpl
			}
		}
	}
	context, _ := GetTemplateContext(entries, links, title, "root", r)
	context.PreviousURL = previousURL
	context.NextURL = nextURL

	var contentBuffer bytes.Buffer
	renderTemplate(&contentBuffer, template, context)
	content, err := ioutil.ReadAll(&contentBuffer)
	if err != nil {
		c.Errorf("Error reading content from buffer: %v", err)
	}
	w.Write(content)
	page_ttl, _ := config.GetInt("page_cache_ttl")
	storeInCache(c, key, content, int(page_ttl))
}
Esempio n. 22
0
func Get(w http.ResponseWriter, r *http.Request, m map[string]interface{}) *Instance {

	c := appengine.NewContext(r)

	startFunc := time.Now()

	if !ii.LastUpdated.IsZero() {

		age := startFunc.Sub(ii.LastUpdated)

		if age < 200*time.Millisecond {
			c.Infof("instance info update too recently: %v, skipping.\n", age)
			return ii
		}

		if age < 1*time.Hour {
			if len(ii.Hostname) > 2 {
				return ii
			}

		}

		c.Infof("instance info update too old: %v, recomputing.\n", age)
	}

	ii.ModuleName = appengine.ModuleName(c)
	ii.InstanceID = appengine.InstanceID()
	ii.VersionFull = appengine.VersionID(c)

	majorMinor := strings.Split(ii.VersionFull, ".")
	if len(majorMinor) != 2 {
		panic("we need a version string of format X.Y")
	}

	ii.VersionMajor = majorMinor[0]
	ii.VersionMinor = majorMinor[1]

	var err = errors.New("dummy creation error message")

	ii.NumInstances, err = module.NumInstances(c, ii.ModuleName, ii.VersionFull)
	if err != nil {
		// this never works with version full
		// we do not log this - but try version major
		err = nil

		if !util_appengine.IsLocalEnviron() {
			ii.NumInstances, err = module.NumInstances(c, ii.ModuleName, ii.VersionMajor)
			util_err.Err_http(w, r, err, true, "get num instances works only live and without autoscale")
		}

	}

	// in auto scaling, google reports "zero" - which can not be true
	// we assume at least 1
	if ii.NumInstances == 0 {
		ii.NumInstances = 1
	}

	// http://[0-2].1.default.libertarian-islands.appspot.com/instance-info

	ii.Hostname, err = appengine.ModuleHostname(c, ii.ModuleName,
		ii.VersionMajor, "")
	util_err.Err_http(w, r, err, false)

	if !util_appengine.IsLocalEnviron() {
		ii.HostnameInst0, err = appengine.ModuleHostname(c, ii.ModuleName,
			ii.VersionMajor, "0")
		if err != nil && (err.Error() == autoScalingErr1 || err.Error() == autoScalingErr2) {
			c.Infof("inst 0: " + autoScalingErrMsg)
			err = nil
		}
		util_err.Err_http(w, r, err, true)

		ii.HostnameInst1, err = appengine.ModuleHostname(c, ii.ModuleName,
			ii.VersionMajor, "1")
		if err != nil && (err.Error() == autoScalingErr1 || err.Error() == autoScalingErr2) {
			c.Infof("inst 1: " + autoScalingErrMsg)
			err = nil
		}
		util_err.Err_http(w, r, err, true)

		ii.HostnameMod02, err = appengine.ModuleHostname(c, "mod02", "", "")
		util_err.Err_http(w, r, err, true)

	}

	ii.LastUpdated = time.Now()

	c.Infof("collectInfo() completed, %v.%v.%v.%v, took %v",
		util.Ellipsoider(ii.InstanceID, 4), ii.VersionMajor, ii.ModuleName,
		ii.Hostname,
		ii.LastUpdated.Sub(startFunc))

	return ii
}