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) }
func TestPutObject(t *testing.T) { gs, bucket := doConfig(t) now := time.UTC() testKey := fmt.Sprintf("test-put-%v.%v.%v-%v.%v.%v", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second) shouldRetry, err := gs.PutObject(&Object{bucket, testKey}, &BufferCloser{bytes.NewBufferString(testObjectContent)}) if shouldRetry { shouldRetry, err = gs.PutObject(&Object{bucket, testKey}, &BufferCloser{bytes.NewBufferString(testObjectContent)}) } if err != nil { t.Fatalf("Failed to put object: %v", err) } // Just stat to check that it actually uploaded, don't bother reading back size, exists, err := gs.StatObject(&Object{bucket, testKey}) if !exists { t.Errorf("Test object doesn't exist!") } if size != int64(len(testObjectContent)) { t.Errorf("Test object size is wrong: \nexpected: %v\nfound: %v\n", len(testObjectContent), size) } }
func (p *MockGoogleClient) handleGetGroupList(req *http.Request) (resp *http.Response, err os.Error) { numGroups := len(p.groupsById) entries := make([]ContactGroup, numGroups) r := NewGroupsFeedResponse() f := r.Feed f.Entries = entries i := 0 for _, v := range p.groupsById { entries[i] = *v i++ } userInfo, _ := p.RetrieveUserInfo() if userInfo != nil { f.Id.Value = userInfo.Guid() f.Author = make([]AtomAuthor, 1) f.Author[0].Email.Value = userInfo.Username() f.Author[0].Name.Value = userInfo.GivenName() f.Title.Value = userInfo.GivenName() + "'s Contact Groups" } f.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT) f.TotalResults.Value = strconv.Itoa(numGroups) f.StartIndex.Value = "1" f.ItemsPerPage.Value = "25" //fmt.Printf("Group List Entry Count: %d\n", numGroups) return createJSONHttpResponseFromObj(req, r) }
func (p *MockGoogleClient) handleCreateGroup(req *http.Request) (resp *http.Response, err os.Error) { //fmt.Printf("calling handleCreateGroup\n") b := NewGroupResponse() err = json.NewDecoder(req.Body).Decode(b) if err != nil { panic(fmt.Sprintf("Error creating group: %s\n", err.String())) resp, _ = createJSONHttpResponseFromObj(req, NewGroupResponse()) resp.Status = "500 INTERNAL SERVER ERROR" resp.StatusCode = http.StatusInternalServerError return } if b.Entry == nil { resp, err = createJSONHttpResponseFromObj(req, NewGroupResponse()) resp.Status = "400 BAD REQUEST" resp.StatusCode = http.StatusBadRequest return } e := b.Entry groupId := p.generateId() e.Id.Value = groupId e.Etag = p.generateEtag() e.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT) p.groupsById[groupId] = e r := NewGroupResponse() r.Entry = e r.Entry.Xmlns = XMLNS_ATOM r.Entry.XmlnsGcontact = XMLNS_GCONTACT r.Entry.XmlnsBatch = XMLNS_GDATA_BATCH r.Entry.XmlnsGd = XMLNS_GD //fmt.Printf("Contact Entry: %v\n", c.Name) return createJSONHttpResponseFromObj(req, r) }
func makeRedirectServer(redirects map[string]string, context *Context) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { key := req.URL.Path[1:] url, exists := redirects[key] if !exists { http.NotFound(w, req) return } /* * I don't use the http.Redirect because it generates HTML and * I don't need that */ w.SetHeader("Location", url) w.WriteHeader(http.StatusMovedPermanently) var stat Statmsg stat.Time = time.UTC() stat.Key = key stat.IP = w.RemoteAddr() stat.Referer = req.Referer stat.UA = req.UserAgent context.Update(&stat) } }
// Used exclusively by S3 to the best of my knowledge... func (self *Signer) SignRequestV1(req *http.Request, canon func(*http.Request) (string, os.Error), exp int64) (err os.Error) { qstring, err := http.ParseQuery(req.URL.RawQuery) if err != nil { return } if exp > 0 { qstring["Expires"] = []string{strconv.Itoa64(time.Seconds() + exp)} } else { qstring["Timestamp"] = []string{time.UTC().Format(ISO8601TimestampFormat)} } qstring["Signature"] = nil, false qstring["AWSAccessKeyId"] = []string{self.AccessKey} req.URL.RawQuery = http.Values(qstring).Encode() can, err := canon(req) if err != nil { return } var sig []byte sig, err = self.SignEncoded(crypto.SHA1, can, base64.StdEncoding) if err == nil { req.URL.RawQuery += "&" + http.Values{"Signature": []string{string(sig)}}.Encode() } return }
func decodeSecureCookie(value string) (user string, session string, err os.Error) { parts := strings.Split(value, "|", 3) if len(parts) != 3 { err = os.NewError("Malformed cookie value") return } val := parts[0] timestamp := parts[1] sig := parts[2] // Check signature if getCookieSig([]byte(val), timestamp) != sig { return "", "", os.NewError("Signature error, cookie is invalid") } // Check time stamp ts, _ := strconv.Atoi64(timestamp) if ts+maxAge < time.UTC().Seconds() { return "", "", os.NewError("Cookie is outdated") } buf := bytes.NewBufferString(val) encoder := base64.NewDecoder(base64.StdEncoding, buf) res, _ := ioutil.ReadAll(encoder) str := string(res) lst := strings.Split(str, "!", -1) if len(lst) != 2 { return "", "", os.NewError("Missing !") } return lst[0], lst[1], nil }
// Adds common parameters to the "params" map, signs the request, // adds the signature to the "params" map and sends the request // to the server. It then unmarshals the response in to the "resp" // parameter using xml.Unmarshal() func (mt *MTurk) query(params map[string]string, operation string, resp interface{}) os.Error { service := MTURK_SERVICE timestamp := time.UTC().Format(TIMESTAMP_FORMAT) params["AWSAccessKeyId"] = mt.Auth.AccessKey params["Service"] = service params["Timestamp"] = timestamp params["Operation"] = operation // make a copy url := *mt.URL sign(mt.Auth, service, operation, timestamp, params) url.RawQuery = multimap(params).Encode() r, err := http.Get(url.String()) if err != nil { return err } dump, _ := http.DumpResponse(r, true) println("DUMP:\n", string(dump)) if r.StatusCode != 200 { return os.NewError(fmt.Sprintf("%d: unexpected status code", r.StatusCode)) } err = xml.Unmarshal(r.Body, resp) r.Body.Close() return err }
// Test time containments. func TestTimeContainments(t *testing.T) { now := time.UTC() years := []int64{2008, 2009, 2010} months := []int{3, 6, 9, 12} days := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} hours := []int{20, 21, 22, 23} minutes := []int{5, 10, 15, 20, 25, 30} seconds := []int{0, 15, 30, 45} weekdays := []int{time.Saturday, time.Sunday} t.Logf("Time is %s\n", now.Format(time.RFC822)) t.Logf("Year in list : %t\n", YearInList(now, years)) t.Logf("Year in range : %t\n", YearInRange(now, 2000, 2005)) t.Logf("Month in list : %t\n", MonthInList(now, months)) t.Logf("Month in range : %t\n", MonthInRange(now, 1, 6)) t.Logf("Day in list : %t\n", DayInList(now, days)) t.Logf("Day in range : %t\n", DayInRange(now, 15, 25)) t.Logf("Hour in list : %t\n", HourInList(now, hours)) t.Logf("Hour in range : %t\n", HourInRange(now, 9, 17)) t.Logf("Minute in list : %t\n", MinuteInList(now, minutes)) t.Logf("Minute in range : %t\n", MinuteInRange(now, 0, 29)) t.Logf("Second in list : %t\n", SecondInList(now, seconds)) t.Logf("Second in range : %t\n", SecondInRange(now, 30, 59)) t.Logf("Weekday in list : %t\n", WeekdayInList(now, weekdays)) t.Logf("Weekday in range: %t\n", WeekdayInRange(now, time.Monday, time.Friday)) }
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) }
func Stamp(output io.WriteCloser, input io.Reader) (err os.Error) { lines := bufio.NewReader(input) line := make([]byte, 0, 256) for { data, pfx, err := lines.ReadLine() if err != nil { break } line = append(line, data...) if pfx { continue } now := time.UTC() _, err = output.Write([]byte(now.Format(time.RFC3339) + " ")) if err != nil { break } if _, err = output.Write(line); err != nil { break } if _, err = output.Write([]byte("\n")); err != nil { break } line = make([]byte, 0, 256) } output.Close() return }
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)) } }
func (sns *SNS) query(topic *Topic, message *Message, params map[string]string, resp interface{}) os.Error { params["Timestamp"] = time.UTC().Format(time.RFC3339) url_, err := url.Parse(sns.Region.SNSEndpoint) if err != nil { return err } sign(sns.Auth, "GET", "/", params, url_.Host) url_.RawQuery = multimap(params).Encode() r, err := http.Get(url_.String()) if err != nil { return err } defer r.Body.Close() //dump, _ := http.DumpResponse(r, true) //println("DUMP:\n", string(dump)) //return nil if r.StatusCode != 200 { return buildError(r) } err = xml.Unmarshal(r.Body, resp) return err }
func (p *FileResource) CreatePath(req Request, cxt Context) (string, Request, Context, int, os.Error) { frc := cxt.(FileResourceContext) if frc.IsDir() { newPath := filepath.Join(frc.FullPath(), string(rand.Int63())) frc2 := NewFileResourceContextWithPath(newPath) for frc2.Exists() { newPath = filepath.Join(frc.FullPath(), string(rand.Int63())) frc2 = NewFileResourceContextWithPath(newPath) } frc = frc2 } else if frc.Exists() { p := frc.FullPath() dir, tail := path.Split(p) ext := path.Ext(tail) basename := tail uniquify := time.UTC().Format(".20060102.150405") if len(ext) > 0 { basename = tail[:len(tail)-len(ext)] + uniquify frc.SetFullPath(path.Join(dir, basename+ext)) for counter := 1; frc.Exists(); counter++ { frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter)+ext)) } } else { basename = basename + uniquify frc.SetFullPath(path.Join(dir, basename)) for counter := 1; frc.Exists(); counter++ { frc.SetFullPath(path.Join(dir, basename+"."+strconv.Itoa(counter))) } } } log.Print("[FileResource]: Will use path ", frc.FullPath()) return frc.FullPath(), req, frc, 0, nil }
// Write an CLF formatted access log to 'logger' func AccessLog(logger *log.Logger) Pipe { return func(conn *Conn, req *http.Request) bool { var remoteHost = req.RemoteAddr // FIXME var ident string = "-" var authuser string = "-" var now *time.Time = time.UTC() var timestamp string = now.Format("[07/Jan/2006:15:04:05 -0700]") var request string = fmt.Sprintf("%s %s %s", req.Method, req.RawURL, req.Proto) var status int = conn.status var size int64 = conn.written var referer string = "-" var userAgent string = "-" if len(req.Referer()) > 0 { referer = req.Referer() } if len(req.UserAgent()) > 0 { userAgent = req.UserAgent() } // Spawn a new goroutine to perform the actual print to the logfile // instead of making the pipeline wait. go func() { logger.Printf("%s %s %s %s \"%s\" %d %d \"%s\" \"%s\"\n", remoteHost, ident, authuser, timestamp, request, status, size, referer, userAgent) }() return true } }
// This function returns true or false, depending on whether the CacheTimeout // value has expired or not. Additionally, it will ensure that we adhere to the // RSS spec's SkipDays and SkipHours values (if Feed.EnforceCacheLimit is set to // true). If this function returns true, you can be sure that a fresh feed // update will be performed. func (this *Feed) CanUpdate() bool { // Make sure we are not within the specified cache-limit. // This ensures we don't request data too often. utc := time.UTC() if utc.Seconds()-this.lastupdate < int64(this.CacheTimeout*60) { return false } // If skipDays or skipHours are set in the RSS feed, use these to see if // we can update. if len(this.Channels) == 0 && this.Type == "rss" { if this.EnforceCacheLimit && len(this.Channels[0].SkipDays) > 0 { for _, v := range this.Channels[0].SkipDays { if v == utc.Weekday { return false } } } if this.EnforceCacheLimit && len(this.Channels[0].SkipHours) > 0 { for _, v := range this.Channels[0].SkipHours { if v == utc.Hour { return false } } } } this.lastupdate = utc.Seconds() return true }
// 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") }
func main() { now := time.UTC() beats := (float64(now.Hour)*(1000.0/24.0) + float64(now.Minute)*(1000.0/(24.0*60.0)) + float64(now.Second)*(1000.0/(24.0*60.0*60.0))) trunc := float32(int(beats*10)) / 10.0 fmt.Printf("@%g\n", trunc) }
// I-M-S > Now? func (p *wmDecisionCore) doV3l15() WMDecision { now := time.UTC().Seconds() t := p.modifiedSince if t != nil && t.Seconds() > now { return v3m16 } return v3l17 }
func createSessionCookie(w http.ResponseWriter, user string) (session string) { session = fmt.Sprintf("s%v", rand.Int31()) value := encodeSecureCookie(user, session, time.UTC().Seconds()) // Cookie cookie := &http.Cookie{Path: "/", Name: "Session", Value: value, Expires: *time.SecondsToUTC(time.UTC().Seconds() + maxAge)} http.SetCookie(w, cookie) return }
// Use RFC1982 to calculate if a signature period is valid. func (s *RR_RRSIG) ValidityPeriod() bool { utc := time.UTC().Seconds() modi := (int64(s.Inception) - utc) / Year68 mode := (int64(s.Expiration) - utc) / Year68 ti := int64(s.Inception) + (modi * Year68) te := int64(s.Expiration) + (mode * Year68) return ti <= utc && utc <= te }
func init() { go func() { for { <-time.After(1000000000) Now = time.Seconds() UTC = time.UTC() } }() }
func UpdateGroup(client oauth2_client.OAuth2Client, userId, projection string, original, value *ContactGroup) (response *GroupResponse, err os.Error) { var useUserId string if len(userId) <= 0 { useUserId = GOOGLE_DEFAULT_USER_ID } else { useUserId = url.QueryEscape(userId) } if len(projection) <= 0 { projection = GOOGLE_DEFAULT_PROJECTION } headers := make(http.Header) headers.Set("GData-Version", "3.0") headers.Set("If-Match", original.Etag) m := make(url.Values) if len(m.Get(CONTACTS_ALT_PARAM)) <= 0 { m.Set(CONTACTS_ALT_PARAM, "json") } uri := GOOGLE_GROUPS_API_ENDPOINT for _, s := range []string{useUserId, projection, original.GroupId()} { if len(s) > 0 { if uri[len(uri)-1] != '/' { uri += "/" } uri += s } } entry := &GroupEntryUpdateRequest{Entry: value} value.Xmlns = XMLNS_ATOM value.XmlnsGcontact = XMLNS_GCONTACT value.XmlnsBatch = XMLNS_GDATA_BATCH value.XmlnsGd = XMLNS_GD value.Etag = original.Etag value.Id = original.Id value.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT) value.Categories = make([]AtomCategory, 1) value.Categories[0].Scheme = ATOM_CATEGORY_SCHEME_KIND value.Categories[0].Term = ATOM_CATEGORY_TERM_GROUP buf, err := json.Marshal(entry) if err != nil { return } resp, _, err := oauth2_client.AuthorizedPutRequestBytes(client, headers, uri, m, buf) if err != nil { return } if resp != nil { if resp.StatusCode >= 400 { b, _ := ioutil.ReadAll(resp.Body) err = os.NewError(string(b)) } else { response = new(GroupResponse) err = json.NewDecoder(resp.Body).Decode(response) } } return }
//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) }
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) }
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 } }
func logResponse(w http.ResponseWriter, r *http.Request) { fmt.Printf( "%s - - [%s] \"%s %s %s\" - - \"%s\" \"%s\"\n", w.RemoteAddr(), time.UTC().Format("10/Jan/2006:15:04:05 -0700"), r.Method, r.URL.Path, r.Proto, r.Referer, r.UserAgent) }
//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) }
func init() { go func() { for { time.Sleep(1000000000) Now = time.Seconds() UTC = time.UTC() } }() }
func (sh *SyncHandler) addErrorToLog(err os.Error) { log.Printf(err.String()) sh.lk.Lock() defer sh.lk.Unlock() sh.recentErrors = append(sh.recentErrors, timestampedError{time.UTC(), err}) if len(sh.recentErrors) > maxErrors { // Kinda lame, but whatever. Only for errors, rare. copy(sh.recentErrors[:maxErrors], sh.recentErrors[1:maxErrors+1]) sh.recentErrors = sh.recentErrors[:maxErrors] } }