当前位置: 首页>>代码示例>>Golang>>正文


Golang Time.UTC函数代码示例

本文整理汇总了Golang中Time.UTC函数的典型用法代码示例。如果您正苦于以下问题:Golang UTC函数的具体用法?Golang UTC怎么用?Golang UTC使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了UTC函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: SetHeaders

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)
}
开发者ID:welterde,项目名称:mudkip,代码行数:26,代码来源:servicecontext.go

示例2: TestPutObject

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)
	}
}
开发者ID:ipeet,项目名称:camlistore,代码行数:27,代码来源:googlestorage_test.go

示例3: handleGetGroupList

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)
}
开发者ID:pombredanne,项目名称:contacts.go,代码行数:26,代码来源:mock.go

示例4: handleCreateGroup

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)
}
开发者ID:pombredanne,项目名称:contacts.go,代码行数:32,代码来源:mock.go

示例5: makeRedirectServer

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)
	}
}
开发者ID:wladh,项目名称:go-redir-ws,代码行数:27,代码来源:ws.go

示例6: SignRequestV1

// 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
}
开发者ID:justinbarry,项目名称:GoAWS,代码行数:32,代码来源:signer.go

示例7: decodeSecureCookie

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
}
开发者ID:AaronO,项目名称:lightwave,代码行数:29,代码来源:server.go

示例8: query

// 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
}
开发者ID:laslowh,项目名称:mturk,代码行数:31,代码来源:mturk.go

示例9: TestTimeContainments

// 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))
}
开发者ID:28240885,项目名称:the-way-to-go_ZH_CN,代码行数:27,代码来源:cgl_test.go

示例10: SetSecureCookie

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)
}
开发者ID:welterde,项目名称:mudkip,代码行数:30,代码来源:cookies.go

示例11: Stamp

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
}
开发者ID:pombredanne,项目名称:s3io,代码行数:28,代码来源:s3io.go

示例12: postHandler

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))
	}
}
开发者ID:vdobler,项目名称:webtest,代码行数:35,代码来源:suite_test.go

示例13: query

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
}
开发者ID:supr,项目名称:sns,代码行数:25,代码来源:sns.go

示例14: CreatePath

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
}
开发者ID:pombredanne,项目名称:webmachine.go,代码行数:33,代码来源:file_resource.go

示例15: AccessLog

// 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
	}
}
开发者ID:andradeandrey,项目名称:webpipes,代码行数:33,代码来源:pipes.go


注:本文中的Time.UTC函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。