Пример #1
0
func (this *ServiceContext) SetHeaders(code, timeout int, ctype string, modified int64) {
	t := time.UTC()
	t = time.SecondsToUTC(t.Seconds() + int64(timeout))
	ts := t.Format(time.RFC1123)

	this.Conn.SetHeader("Cache-Control", fmt.Sprintf("max-age=%d; must-revalidate", timeout))
	this.Conn.SetHeader("Expires", fmt.Sprintf("%s GMT", ts[0:len(ts)-4]))

	if modified > 0 {
		t = time.SecondsToUTC(modified)
	} else {
		t = time.UTC()
	}

	ts = t.Format(time.RFC1123)

	this.Conn.SetHeader("Last-Modified", fmt.Sprintf("%s GMT", ts[0:len(ts)-4]))
	this.Conn.SetHeader("Content-Type", ctype)
	this.Conn.SetHeader("Server", context.Config().ServerName)

	if this.Compressed {
		this.Conn.SetHeader("Content-Encoding", "gzip")
	}

	this.Conn.WriteHeader(code)
}
Пример #2
0
func (self *Generation) String() string {
	r := fmt.Sprintf("Generation [%s-%s]", time.SecondsToUTC(self.startEpoch), time.SecondsToUTC(self.startEpoch+GenerationSize))
	for key, _ := range self.inhabitants {
		r += fmt.Sprintf("\n %s", key)
	}
	return r
}
Пример #3
0
func TestCRLCreation(t *testing.T) {
	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
	block, _ = pem.Decode([]byte(pemCertificate))
	cert, _ := ParseCertificate(block.Bytes)

	now := time.SecondsToUTC(1000)
	expiry := time.SecondsToUTC(10000)

	revokedCerts := []pkix.RevokedCertificate{
		{
			SerialNumber:   big.NewInt(1),
			RevocationTime: now,
		},
		{
			SerialNumber:   big.NewInt(42),
			RevocationTime: now,
		},
	}

	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
	if err != nil {
		t.Errorf("error creating CRL: %s", err)
	}

	_, err = ParseDERCRL(crlBytes)
	if err != nil {
		t.Errorf("error reparsing CRL: %s", err)
	}
}
Пример #4
0
func TestCreateSelfSignedCertificate(t *testing.T) {
	random := rand.Reader

	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, err := ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		t.Errorf("Failed to parse private key: %s", err)
		return
	}

	template := Certificate{
		SerialNumber: []byte{1},
		Subject: Name{
			CommonName:   "test.example.com",
			Organization: []string{"Acme Co"},
		},
		NotBefore: time.SecondsToUTC(1000),
		NotAfter:  time.SecondsToUTC(100000),

		SubjectKeyId: []byte{1, 2, 3, 4},
		KeyUsage:     KeyUsageCertSign,

		BasicConstraintsValid: true,
		IsCA:     true,
		DNSNames: []string{"test.example.com"},

		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
		PermittedDNSDomains: []string{".example.com", "example.com"},
	}

	derBytes, err := CreateCertificate(random, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		t.Errorf("Failed to create certificate: %s", err)
		return
	}

	cert, err := ParseCertificate(derBytes)
	if err != nil {
		t.Errorf("Failed to parse certificate: %s", err)
		return
	}

	if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
		t.Errorf("Failed to parse policy identifiers: got:%#v want:%#v", cert.PolicyIdentifiers, template.PolicyIdentifiers)
	}

	if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
		t.Errorf("Failed to parse name constraints: %#v", cert.PermittedDNSDomains)
	}

	err = cert.CheckSignatureFrom(cert)
	if err != nil {
		t.Errorf("Signature verification failed: %s", err)
		return
	}
}
Пример #5
0
func (ctx Context) SetCookie(key string, val string, exp int64) {
	var utc *time.Time
	if exp == 0 {
		utc = time.SecondsToUTC(2147483647) // year 2038
	} else {
		utc = time.SecondsToUTC(time.UTC().Seconds() + exp)
	}
	cookie := fmt.Sprintf("%s=%s; expires=%s", key, val, webTime(utc))
	ctx.SetHeader("Set-Cookie", cookie)
}
Пример #6
0
func main() {
	flag.Parse()

	urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
	if err != nil {
		log.Exitf("failed to open /dev/urandom: %s", err)
		return
	}

	priv, err := rsa.GenerateKey(urandom, 1024)
	if err != nil {
		log.Exitf("failed to generate private key: %s", err)
		return
	}

	now := time.Seconds()

	template := x509.Certificate{
		SerialNumber: []byte{0},
		Subject: x509.Name{
			CommonName:   *hostName,
			Organization: "Acme Co",
		},
		NotBefore: time.SecondsToUTC(now - 300),
		NotAfter:  time.SecondsToUTC(now + 60*60*24*365), // valid for 1 year.

		SubjectKeyId: []byte{1, 2, 3, 4},
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

	derBytes, err := x509.CreateCertificate(urandom, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		log.Exitf("Failed to create certificate: %s", err)
		return
	}

	certOut, err := os.Open("cert.pem", os.O_WRONLY|os.O_CREAT, 0644)
	if err != nil {
		log.Exitf("failed to open cert.pem for writing: %s", err)
		return
	}
	pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
	certOut.Close()
	log.Print("written cert.pem\n")

	keyOut, err := os.Open("key.pem", os.O_WRONLY|os.O_CREAT, 0600)
	if err != nil {
		log.Print("failed to open key.pem for writing:", err)
		return
	}
	pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
	keyOut.Close()
	log.Print("written key.pem\n")
}
Пример #7
0
//Sets a cookie -- duration is the amount of time in seconds. 0 = forever
func (ctx *Context) SetCookie(name string, value string, age int64) {
	var utctime *time.Time
	if age == 0 {
		// 2^31 - 1 seconds (roughly 2038)
		utctime = time.SecondsToUTC(2147483647)
	} else {
		utctime = time.SecondsToUTC(time.UTC().Seconds() + age)
	}
	cookie := fmt.Sprintf("%s=%s; expires=%s", name, value, webTime(utctime))
	ctx.SetHeader("Set-Cookie", cookie, false)
}
Пример #8
0
func (p *viewAccountContext) LastModified() *time.Time {
	var lastModified *time.Time
	if p.user != nil && p.user.ModifiedAt != 0 {
		lastModified = time.SecondsToUTC(p.user.ModifiedAt)
	} else if p.consumer != nil && p.consumer.ModifiedAt != 0 {
		lastModified = time.SecondsToUTC(p.consumer.ModifiedAt)
	} else if p.externalUser != nil && p.externalUser.ModifiedAt != 0 {
		lastModified = time.SecondsToUTC(p.externalUser.ModifiedAt)
	}
	return lastModified
}
Пример #9
0
func main() {
	flag.Parse()
	timestamp := time.Seconds()

	if len(*hostname) == 0 {
		ErrorF("Error: Missing -hostname parameter.\n")
	}

	fmt.Printf(">>> Generating Private Key: %s\n", *hostname+".key.pem")
	private_key, error := rsa.GenerateKey(rand.Reader, *bits)

	if error != nil {
		ErrorF("Error: Unable to generate private key: %s\n", error)
	}

	private_key_file, error := os.OpenFile(*hostname+".key.pem", os.O_WRONLY|os.O_CREATE, 0600)

	if error != nil {
		ErrorF("Error: Unable to open %s for writing: %s\n", *hostname+".key.pem", error)
	}

	defer private_key_file.Close()

	pem.Encode(private_key_file, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(private_key)})

	template := x509.Certificate{
		SerialNumber: []byte{0},
		Subject: x509.Name{
			CommonName:   *hostname,
			Organization: []string{*organization},
		},
		NotBefore:    time.SecondsToUTC(timestamp),
		NotAfter:     time.SecondsToUTC(365*24*60*60 + timestamp),
		SubjectKeyId: []byte{1, 3, 3, 7},
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
	}

	fmt.Printf(">>> Generating Certificate: %s\n", *hostname+".pem")
	certificate, error := x509.CreateCertificate(rand.Reader, &template, &template, &private_key.PublicKey, private_key)

	if error != nil {
		ErrorF("Error: Unable to generate certificate: %s\n", error)
	}

	certificate_file, error := os.OpenFile(*hostname+".pem", os.O_WRONLY|os.O_CREATE, 0644)

	if error != nil {
		ErrorF("Error: Unable to open %s for writing: %s\n", *hostname+".pem", error)
	}

	defer certificate_file.Close()

	pem.Encode(certificate_file, &pem.Block{Type: "CERTIFICATE", Bytes: certificate})
}
Пример #10
0
///func parseActDetail(c appengine.Context, r *io.ReadCloser, res *ActDetail) (*ActDetail, os.Error) {
func parseActDetail(c appengine.Context, res *ActDetail) (*ActDetail, os.Error) {
	tmp := strings.NewReader(sampleActHtml)
	r := &tmp
	n, err := html.Parse(*r)
	if err != nil {
		c.Errorf("%s", err.String())
		return nil, err
	}

	nc := NewCursor(n)
	nc = nc.FindById("body1")
	nc.Prune()

	curr := nc.FindText("Activity Type:").Parent().NextSibling().Node.Child[0]
	res.Type = curr.Data

	curr = nc.FindText("Name:").Parent().NextSibling().Node.Child[0]
	res.Name = curr.Data

	curr = nc.FindText("Description:").Parent().NextSibling().Node.Child[0]
	res.Desc = curr.Data

	curr = nc.FindText("Location:").Parent().NextSibling().Node.Child[0]
	res.Location = curr.Data

	curr = nc.FindText("Start Date and Time:").Parent().NextSibling().Node.Child[0]
	res.Start, err = time.Parse("02 Jan 2006\u00a015:04", curr.Data)
	res.Start = time.SecondsToUTC(res.Start.Seconds())
	if err != nil {
		return nil, err
	}

	curr = nc.FindText("Finish Date and Time:").Parent().NextSibling().Node.Child[0]
	res.End, err = time.Parse("02 Jan 2006\u00a015:04", curr.Data)
	res.End = time.SecondsToUTC(res.End.Seconds())
	if err != nil {
		return nil, err
	}

	curr = nc.FindText("No of Cadets:").Parent().NextSibling().Node.Child[0]
	res.NCadets, err = strconv.Atoi(curr.Data)
	if err != nil {
		return nil, err
	}

	curr = nc.FindText("No of Staff:").Parent().NextSibling().Node.Child[0]
	res.NStaff, err = strconv.Atoi(curr.Data)
	if err != nil {
		return nil, err
	}

	return res, nil
}
Пример #11
0
//Sets a cookie -- duration is the amount of time in seconds.
// 0 = forever, persistent
// <0 = omit expires attribute, i.e. expire at end of browser session
func (ctx *Context) SetCookie(name string, value string, age int64) {
	cookie := fmt.Sprintf("%s=%s", name, value)
	if age == 0 {
		// 2^31 - 1 seconds (roughly 2038)
		utctime := time.SecondsToUTC(2147483647)
		cookie += fmt.Sprintf("; expires=%s", webTime(utctime))
	} else if age > 0 {
		utctime := time.SecondsToUTC(time.UTC().Seconds() + age)
		cookie += fmt.Sprintf("; expires=%s", webTime(utctime))
	}
	cookie += fmt.Sprintf("; path=/")
	ctx.SetHeader("Set-Cookie", cookie, false)
}
Пример #12
0
func (p *HtmlDirectoryListing) OutputTo(req Request, cxt Context, writer io.Writer, resp ResponseWriter) {
	result := new(htmlDirectoryEntryResult)
	result.Path = p.urlPath
	result.Tail = path.Base(p.urlPath)
	var err os.Error
	defer func() {
		if p.file != nil {
			p.file.Close()
			p.file = nil
		}
	}()
	if p.file == nil {
		p.file, err = os.Open(p.fullPath)
		if err != nil {
			result.Message = err.String()
			result.Result = make([]htmlDirectoryEntry, 0)
			HTML_DIRECTORY_LISTING_ERROR_TEMPLATE.Execute(writer, result)
			return
		}
	}
	fileInfos, err := p.file.Readdir(-1)
	if err != nil {
		result.Message = err.String()
		result.Result = make([]htmlDirectoryEntry, 0)
		HTML_DIRECTORY_LISTING_ERROR_TEMPLATE.Execute(writer, result)
		return
	}
	entries := make([]htmlDirectoryEntry, len(fileInfos))
	for i, fileInfo := range fileInfos {
		entries[i].Filename = fileInfo.Name
		entries[i].Path = path.Join(p.urlPath, fileInfo.Name)
		entries[i].Size = fileInfo.Size
		entries[i].IsDirectory = fileInfo.IsDirectory()
		if fileInfo.IsDirectory() {
			entries[i].IsDirectory = true
			entries[i].Size = 0
		} else {
			entries[i].IsDirectory = false
			entries[i].Size = fileInfo.Size
		}
		entries[i].LastModified = time.SecondsToUTC(int64(fileInfo.Mtime_ns / 1e9)).Format(time.ANSIC)
	}
	dirInfo, _ := p.file.Stat()
	if dirInfo != nil {
		result.LastModified = time.SecondsToUTC(int64(dirInfo.Mtime_ns / 1e9)).Format(time.ANSIC)
	}
	result.Status = "success"
	result.Message = ""
	result.Result = entries
	HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE.Execute(writer, result)
}
Пример #13
0
func postHandler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if cv := req.FormValue("cookie"); cv != "" {
		trace("postHandler recieved param cookie %s.", cv)
		cp := strings.SplitN(cv, "=", 2)
		if cp[1] != "-DELETE-" {
			exp := time.SecondsToUTC(time.UTC().Seconds() + 7*24*3600).Format(http.TimeFormat) // Now + 7 days
			w.Header().Set("Set-Cookie", fmt.Sprintf("%s=%s; Path=/de/index; expires=%s; Domain=my.domain.org; Secure;", cp[0], cp[1], exp))
		} else {
			trace("post-handler: Deleting cookie %s\n", cp[0])
			w.Header().Set("Set-Cookie", fmt.Sprintf("%s=%s; Path=/de/index; MaxAge=-1; Domain=my.domain.org; Secure;", cp[0], "X"))
		}
	}
	t := req.FormValue("q")
	if req.Method != "POST" {
		fmt.Printf("====== called /post with GET! ======\n")
	}

	_, header, err := req.FormFile("datei")
	if err == nil {
		info("Recieved datei: %s. %v", header.Filename, header.Filename == "file äöü 1.txt")
	}

	if t != "" {
		// w.Header().Set("Location", "http://localhost:54123/"+t)
		// w.Header().Set("Location", "localhost:54123/"+t)
		w.Header().Set("Location", "/"+t)
		w.WriteHeader(302)
	} else {
		text := req.FormValue("text")
		w.WriteHeader(200)
		body := "<html><body><h1>Post Page</h1><p>t = " + html.EscapeString(text) + "</p></body></html>"
		w.Write([]byte(body))
	}
}
Пример #14
0
func googleDateTimeStringToDsocial(s string) (d *DateTime) {
	if len(s) == 10 {
		// YYYY-MM-DD
		d = new(DateTime)
		year, _ := strconv.Atoi(s[0:4])
		month, _ := strconv.Atoi(s[5:7])
		day, _ := strconv.Atoi(s[8:10])
		d.Year = int16(year)
		d.Month = int8(month)
		d.Day = int8(day)
	} else if len(s) == 7 {
		t, err := time.Parse("--01-02", s)
		if err == nil && t != nil {
			d = new(DateTime)
			d.Month = int8(t.Month)
			d.Day = int8(t.Day)
		}
	} else if len(s) == 25 {
		// YYYY-MM-DDTHH:MM:SS-05:00
		t, err := time.Parse("2006-01-02T15:04:05-07:00", s)
		if err == nil && t != nil {
			t2 := time.SecondsToUTC(t.Seconds())
			d = new(DateTime)
			d.Year = int16(t2.Year)
			d.Month = int8(t2.Month)
			d.Day = int8(t2.Day)
			d.Hour = int8(t2.Hour)
			d.Minute = int8(t2.Minute)
			d.Second = int8(t2.Second)
		}
	}
	return
}
Пример #15
0
func (sh *Handler) serveRecentPermanodes(rw http.ResponseWriter, req *http.Request) {
	ret := jsonMap()
	defer httputil.ReturnJson(rw, ret)

	ch := make(chan *Result)
	errch := make(chan os.Error)
	go func() {
		errch <- sh.index.GetRecentPermanodes(ch, []*blobref.BlobRef{sh.owner}, 50)
	}()

	dr := sh.NewDescribeRequest()

	recent := jsonMapList()
	for res := range ch {
		dr.Describe(res.BlobRef, 2)
		jm := jsonMap()
		jm["blobref"] = res.BlobRef.String()
		jm["owner"] = res.Signer.String()
		t := time.SecondsToUTC(res.LastModTime)
		jm["modtime"] = t.Format(time.RFC3339)
		recent = append(recent, jm)
	}

	err := <-errch
	if err != nil {
		// TODO: return error status code
		ret["error"] = err.String()
		return
	}

	ret["recent"] = recent
	dr.PopulateJSON(ret)
}
Пример #16
0
func (fi *FakeIndex) nextDate() *time.Time {
	fi.cllk.Lock()
	fi.clock++
	clock := fi.clock
	fi.cllk.Unlock()
	return time.SecondsToUTC(clock)
}
Пример #17
0
func SetSecureCookie(rw http.ResponseWriter, name, val, path string, timeout int64) {
	var buf bytes.Buffer

	e := base64.NewEncoder(base64.StdEncoding, &buf)
	e.Write([]byte(val))
	e.Close()

	ts := strconv.Itoa64(time.Seconds())
	data := strings.Join([]string{buf.String(), ts, getCookieSig(buf.Bytes(), ts)}, "|")

	var cookie string

	// Timeout of -1 is a special case that omits the entire 'expires' bit.
	// This is used for cookies which expire as soon as a user's session ends.
	if timeout != -1 {
		t := time.UTC()
		t = time.SecondsToUTC(t.Seconds() + timeout)
		ts = t.Format(time.RFC1123)
		ts = ts[0:len(ts)-3] + "GMT"
		cookie = fmt.Sprintf("%s=%s; expires=%s; path=%s", name, data, ts, path)
	} else {
		cookie = fmt.Sprintf("%s=%s; path=%s", name, data, path)
	}

	if context.Config().Secure {
		cookie += "; secure"
	}

	rw.SetHeader("Set-Cookie", cookie)
}
Пример #18
0
func Crawl(pool *mgo.Session, du *DigestwUser, tl *TwTimeLine, resolveURL bool, done chan<- int) {
	defer func() { done <- 0 }()
	sess := pool.New()
	defer sess.Close()
	sa := NewStatsAll(du.TwUser.Screen_Name, sess)
	var sid, first, last int64
	for k, v := range *tl {
		tmpTime, _ := time.Parse(time.RubyDate, v.Created_at)
		tmpSec := tmpTime.Seconds()
		if du.UTC_Offset != nil {
			tmpSec += *du.UTC_Offset
			v.Created_at = time.SecondsToUTC(tmpSec).Format(time.RubyDate)
		}
		if k == 0 {
			sid = v.Id
			last = tmpSec
		}
		addStats(sa, &v, resolveURL)
		if k == (len(*tl) - 1) {
			first = tmpSec
		}
		//log.Printf("id:%d", v.Id)
	}
	sa.Foreach(update)
	// decide to the next execution time
	du.SinceId = strconv.Itoa64(sid)
	du.NextSeconds = time.Seconds() + (last - first)
	if _, err := du.Upsert(sess); err != nil {
		log.Print(err)
	}
}
Пример #19
0
func (c *Cookie) String() string {
	var b bytes.Buffer
	b.WriteString(c.Name)
	b.WriteRune('=')
	b.WriteString(c.Value)
	if c.MaxAge < 0 {
		// A date in the past will delete the cookie.
		b.WriteString("; Expires=Mon, 02 Jan 2006 15:04:05 GMT")
	}
	if c.MaxAge > 0 {
		// Write expires attribute because some browsers do not support max-age.
		b.WriteString("; Expires=")
		b.WriteString(time.SecondsToUTC(time.Seconds() + int64(c.MaxAge)).Format(TimeLayout))
	}
	if c.Path != "" {
		b.WriteString("; Path=")
		b.WriteString(c.Path)
	}
	if c.Domain != "" {
		b.WriteString("; Domain=")
		b.WriteString(c.Domain)
	}
	if c.Secure {
		b.WriteString("; Secure")
	}
	if c.HttpOnly {
		b.WriteString("; HttpOnly")
	}
	return b.String()
}
Пример #20
0
func (sd SportsData) ParsedStartTime() *time.Time {
	t, _ := time.Parse(time.RFC3339, sd.StartTime)
	// Hack to make sure that the weekday is set correctly.
	// Found here: http://code.google.com/p/go/issues/detail?id=2291
	t = time.SecondsToUTC(t.Seconds())
	return t
}
Пример #21
0
func TestCreateSelfSignedCertificate(t *testing.T) {
	urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
	if err != nil {
		t.Errorf("failed to open /dev/urandom")
	}

	block, _ := pem.Decode([]byte(pemPrivateKey))
	priv, err := ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		t.Errorf("Failed to parse private key: %s", err)
		return
	}

	template := Certificate{
		SerialNumber: []byte{1},
		Subject: Name{
			CommonName:   "test.example.com",
			Organization: "Acme Co",
		},
		NotBefore: time.SecondsToUTC(1000),
		NotAfter:  time.SecondsToUTC(100000),

		SubjectKeyId: []byte{1, 2, 3, 4},
		KeyUsage:     KeyUsageCertSign,

		BasicConstraintsValid: true,
		IsCA:     true,
		DNSNames: []string{"test.example.com"},
	}

	derBytes, err := CreateCertificate(urandom, &template, &template, priv)
	if err != nil {
		t.Errorf("Failed to create certificate: %s", err)
		return
	}

	cert, err := ParseCertificate(derBytes)
	if err != nil {
		t.Errorf("Failed to parse certificate: %s", err)
		return
	}
	err = cert.CheckSignatureFrom(cert)
	if err != nil {
		t.Errorf("Signature verification failed: %s", err)
		return
	}
}
Пример #22
0
// Translate the RRSIG's incep. and expir. time to the correct date.
// Taking into account serial arithmetic (RFC 1982)
func timeToDate(t uint32) string {
	utc := time.UTC().Seconds()
	mod := (int64(t) - utc) / Year68

	// If needed assume wrap around(s)
	ti := time.SecondsToUTC(int64(t) + (mod * Year68)) // abs()? TODO
	return ti.Format("20060102150405")
}
Пример #23
0
func FormatTime(nanoSeconds int64, utc bool, format string) string {
	seconds := nanoSeconds / 1000000000
	if utc {
		return time.SecondsToUTC(seconds).Format(format)
	} else {
		return time.SecondsToLocalTime(seconds).Format(format)
	}
	panic("unreachable code")
}
Пример #24
0
func readTestFile(t *testing.T, ft ZipTestFile, f *File) {
	if f.Name != ft.Name {
		t.Errorf("name=%q, want %q", f.Name, ft.Name)
	}

	mtime, err := time.Parse("01-02-06 15:04:05", ft.Mtime)
	if err != nil {
		t.Error(err)
		return
	}
	if got, want := f.Mtime_ns()/1e9, mtime.Seconds(); got != want {
		t.Errorf("%s: mtime=%s (%d); want %s (%d)", f.Name, time.SecondsToUTC(got), got, mtime, want)
	}

	testFileMode(t, f, ft.Mode)

	size0 := f.UncompressedSize

	var b bytes.Buffer
	r, err := f.Open()
	if err != nil {
		t.Error(err)
		return
	}

	if size1 := f.UncompressedSize; size0 != size1 {
		t.Errorf("file %q changed f.UncompressedSize from %d to %d", f.Name, size0, size1)
	}

	_, err = io.Copy(&b, r)
	if err != nil {
		t.Error(err)
		return
	}
	r.Close()

	var c []byte
	if len(ft.Content) != 0 {
		c = ft.Content
	} else if c, err = ioutil.ReadFile("testdata/" + ft.File); err != nil {
		t.Error(err)
		return
	}

	if b.Len() != len(c) {
		t.Errorf("%s: len=%d, want %d", f.Name, b.Len(), len(c))
		return
	}

	for i, b := range b.Bytes() {
		if b != c[i] {
			t.Errorf("%s: content[%d]=%q want %q", f.Name, i, b, c[i])
			return
		}
	}
}
Пример #25
0
//Sets a cookie -- duration is the amount of time in seconds. 0 = forever
func (ctx *Context) SetCookie(name string, value string, age int64) {
	if age == 0 {
		//do some really long time
	}

	utctime := time.UTC()
	utc1 := time.SecondsToUTC(utctime.Seconds() + 60*30)
	cookie := fmt.Sprintf("%s=%s; expires=%s", name, value, webTime(utc1))
	ctx.SetHeader("Set-Cookie", cookie, false)
}
Пример #26
0
func redirectHandler(w http.ResponseWriter, req *http.Request) {

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

	switch lastPath(req) {
	case "redirect", "":
		w.Header().Set("Location", "http://localhost:54123/redirect/first")
		w.Header().Add("Set-Cookie", "rda=rda; Path=/")
		w.Header().Add("Set-Cookie", "clearme=eraseme; Path=/")
		w.WriteHeader(302)
		return
	case "first":
		w.Header().Set("Location", "http://localhost:54123/redirect/second")
		w.Header().Set("Set-Cookie", "rdb=rdb; Path=/redirect")
		w.WriteHeader(302)
		return
	case "second":
		w.Header().Set("Location", "http://localhost:54123/redirect/third")
		w.Header().Set("Set-Cookie", "rdc=rdc; Path=/otherpath")
		w.WriteHeader(302)
		return
	case "third":
		w.Header().Set("Location", "http://localhost:54123/redirect/fourth")
		exp := time.SecondsToUTC(time.UTC().Seconds() - 10000).Format(http.TimeFormat)
		w.Header().Set("Set-Cookie", "clearme=; Path=/; Max-Age=0; Expires="+exp)
		w.WriteHeader(302)
		return
	case "fourth":
		w.Header().Set("Location", "http://localhost:54123/redirect/last")
		rdav, rdae := req.Cookie("rda")
		rdbv, rdbe := req.Cookie("rdb")
		_, rdce := req.Cookie("rdc")
		_, cme := req.Cookie("clearme")
		if rdae == nil && rdav.Value == "rda" && rdbe == nil && rdbv.Value == "rdb" && rdce != nil && cme != nil {
			w.WriteHeader(302)
		} else {
			w.WriteHeader(500)
			body := "<html><body><h1>Wrong cookies</h1><pre>"
			for _, c := range req.Cookies() {
				body += fmt.Sprintf("\n%#v\n", *c)
			}
			body += "</pre></body></html>"
			w.Write([]byte(body))
		}
		return
	case "last":
		w.WriteHeader(200)
		w.Write([]byte("<html><body><h1>No more redirects.</h1></body></html>"))
		return
	default:
		w.WriteHeader(404)
		w.Write([]byte("<html><body><h1>Oooops..." + lastPath(req) + "</h1></body></html>"))
		return
	}
}
Пример #27
0
func JSONValueToTime(value interface{}, format string) *time.Time {
	switch v := value.(type) {
	case nil, bool, JSONArray, JSONObject, []interface{}, map[string]interface{}:
		return nil
	case string:
		t, _ := time.Parse(format, v)
		return t
	case int64:
		return time.SecondsToUTC(v)
	case int:
		return time.SecondsToUTC(int64(v))
	case float64:
		return time.SecondsToUTC(int64(v))
	case time.Time:
		return &v
	case *time.Time:
		return v
	}
	return nil
}
Пример #28
0
func rfc3339FromNanos(epochnanos int64) string {
	nanos := epochnanos % 1e9
	esec := epochnanos / 1e9
	t := time.SecondsToUTC(esec)
	timeStr := t.Format(time.RFC3339)
	if nanos == 0 {
		return timeStr
	}
	nanoStr := fmt.Sprintf("%09d", nanos)
	nanoStr = strings.TrimRight(nanoStr, "0")
	return timeStr[:len(timeStr)-1] + "." + nanoStr + "Z"
}
Пример #29
0
//Sets a cookie -- duration is the amount of time in seconds. 0 = forever
func (ctx *Context) SetCookie(name string, value string, age int64) {
	if age == 0 {
		//do some really long time
	}

	utctime := time.UTC()
	utc1 := time.SecondsToUTC(utctime.Seconds() + 60*30)
	expires := utc1.Format(time.RFC1123)
	expires = expires[0:len(expires)-3] + "GMT"
	cookie := fmt.Sprintf("%s=%s; expires=%s", name, value, expires)
	ctx.SetHeader("Set-Cookie", cookie, false)
}
Пример #30
0
func (p *JsonDirectoryListing) OutputTo(req Request, cxt Context, writer io.Writer, resp ResponseWriter) {
	result := new(jsonDirectoryEntryResult)
	result.Path = p.urlPath
	var err os.Error
	defer func() {
		if p.file != nil {
			p.file.Close()
			p.file = nil
		}
	}()
	if p.file == nil {
		p.file, err = os.Open(p.fullPath)
		if err != nil {
			result.Status = "error"
			result.Message = err.String()
			result.Result = make([]jsonDirectoryEntry, 0)
			encoder := json.NewEncoder(writer)
			encoder.Encode(result)
			return
		}
	}
	fileInfos, err := p.file.Readdir(-1)
	if err != nil {
		result.Status = "error"
		result.Message = err.String()
		result.Result = make([]jsonDirectoryEntry, 0)
		encoder := json.NewEncoder(writer)
		encoder.Encode(result)
		return
	}
	entries := make([]jsonDirectoryEntry, len(fileInfos))
	for i, fileInfo := range fileInfos {
		entries[i].Filename = fileInfo.Name
		entries[i].Path = path.Join(p.urlPath, fileInfo.Name)
		entries[i].Size = fileInfo.Size
		entries[i].IsDirectory = fileInfo.IsDirectory()
		if fileInfo.IsDirectory() {
			entries[i].IsDirectory = true
			entries[i].Size = 0
		} else {
			entries[i].IsDirectory = false
			entries[i].Size = fileInfo.Size
		}
		entries[i].LastModified = time.SecondsToUTC(int64(fileInfo.Mtime_ns / 1e9)).Format(time.RFC3339)
	}
	result.Status = "success"
	result.Message = ""
	result.Result = entries
	encoder := json.NewEncoder(writer)
	encoder.Encode(result)
}