Пример #1
0
func main() {
	c := make(chan int)
	go func() {
		time.Sleep(3 * 1e9) //time in nanos. 3 secs
		x := <-c
		fmt.Println("received at", time.LocalTime())
	}()

	fmt.Println("sending at", time.LocalTime())
	c <- 10
	fmt.Println("sent at", time.LocalTime())
}
Пример #2
0
func main() {
	fmt.Print("Go runs on")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd,openbsd,plan9,windows
		fmt.Printf("%s.", os)
	}

	fmt.Println(runtime.GOROOT)

	/**
	Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
	(For example,
	switch i {
		case 0:
		case f():
	}
	does not call f if i==0.)
	**/
	fmt.Println("When`s Saturday?")
	today := time.LocalTime().Weekday
	switch time.Saturday {
	case today + 0:
		fmt.Println("Today.")
	case today + 1:
		fmt.Println("Tomorrow.")
	case today + 2:
		fmt.Println("In tow days.")
	default:
		fmt.Println("Too far away.")
	}

	/**
	Switch without a condition is the same as switch true.
	**/
	t := time.LocalTime()
	switch {
	case t.Hour < 12:
		fmt.Println("Good morning!")
	case t.Hour < 17:
		fmt.Println("Good afternoon.")
	default:
		fmt.Println("Good evening.")
	}
}
Пример #3
0
func Start(ctx *web.Context, handler *MHandler) *Session {
	session := new(Session)
	session.handler = handler
	session.handler.Clean()
	old := false
	if ctx.Cookies != nil {
		if id, exists := ctx.Cookies["bloody_sess"]; exists {
			session.id = id
			old = true
		}
	}
	if !old {
		// Starts new session
		session.generateId()
		session.handler.Store(session.GetID(), nil)
	}
	rt := session.handler.Retrieve(session.GetID())
	json.Unmarshal(rt.SessionData, &session.Data)
	if session.Data == nil {
		t := make(map[string]interface{})
		session.Data = t
	}
	ctx.SetCookie("bloody_sess", session.GetID(), time.LocalTime().Seconds()+3600)
	return session
}
Пример #4
0
// This is the FileLogWriter's output method
func (flw *FileLogWriter) LogWrite(rec *LogRecord) (n int, err os.Error) {
	flw.lock.Lock()
	defer flw.lock.Unlock()

	// First, check if we've gone over any of our rotate triggers
	if flw.Good() {
		if (flw.maxlines > 0 && flw.maxlines_curlines >= flw.maxlines) ||
			(flw.maxsize > 0 && flw.maxsize_cursize >= flw.maxsize) ||
			(flw.daily && time.LocalTime().Day != flw.daily_opendate) {
			flw.intRotate()
		}
	}

	// Make sure the writer is (still) good
	if !flw.Good() {
		return -1, os.NewError("File was not opened successfully")
	}

	// Perform the write
	n, err = flw.file.Write([]byte(FormatLogRecord(flw.format, rec)))

	// Update the counts
	if err == nil {
		flw.maxlines_curlines++
		flw.maxsize_cursize += n
	}

	return n, err
}
Пример #5
0
func (myRouter *routerStruct) addOurReceivedField(fd *os.File, mailfrom string, rcptto string, helo string, ehlo string, uid string, fn822 string, addReturnPath bool) {

	var wi, fr string = "", ""

	if len(ehlo) != 0 {
		wi = "ESMTP"
		fr = ehlo
	} else {
		wi = "SMTP"
		fr = helo
	}

	dateTime := time.LocalTime().Format("Mon, 02 Jan 2006 15:04:05 -0700")

	if addReturnPath == true {
		r := fmt.Sprintf("Return-Path: <%s>\r\n", mailfrom)
		fd.Write([]byte(r))
	}

	r := fmt.Sprintf("Received: from %s\r\n\tby %s with %s id %s\r\n\tfor %s;\r\n\t%s\r\n",
		fr,
		G_hostname,
		wi,
		uid,
		rcptto,
		dateTime)

	fd.Write([]byte(r))
}
Пример #6
0
func tch_handleToday(session *BlogSession, items []string) string {
	if len(items) != 1 {
		return "syntax: today\n"
	}

	today_t := time.LocalTime()
	today_t.Hour = 0
	today_t.Minute = 0
	today_t.Second = 0

	today := today_t.Seconds()
	tomorrow := today + (24 * 60 * 60)

	//GetPostsForTimespan(start_timestamp, end_timestamp int64) (posts []BlogPost, err os.Error)

	fmt.Printf("today: %d | tomorro: %d\n", today, tomorrow)

	posts, err := session.Db().GetPostsForTimespan(today, tomorrow, 1)
	if err != nil {
		return err.String() + "\n"
	}

	//post.Comments, _ = session.Db().GetComments(post.Id)
	s := ""
	for _, post := range posts {
		s += session.BlogFormatter().FormatPost(&post, false)
		s += "\n"
	}

	return s
}
Пример #7
0
func index(ctx *web.Context) string {
	posts := postsForMonth(time.LocalTime()) //Db.GetLastNPosts(10)
	s := RenderHeader()
	s += RenderPosts(&posts)
	s += RenderFooter()
	return s
}
Пример #8
0
func Command(cmd string) []string {
	command := []byte(strings.ToLower(cmd))
	if what_time.Match(command) {
		current_time := time.LocalTime()
		formatted_time := current_time.Format(time.Kitchen)
		return []string{formatted_time}
	} else if who_are_you.Match(command) {
		return []string{"I am Gopher, I'm here to help."}
	} else if cmd == "gopher quit" {
		os.Exit(0)
	} else if matches := gist.FindSubmatch(command); matches != nil {
		for _, match := range matches {
			fmt.Printf("Match: %s\n", string(match))
		}

		if len(matches) > 1 {
			gist_id, err := strconv.Atoui(string(matches[1]))
			if err != nil {
				fmt.Printf("Could not parse the gist_id: %s\n", string(matches[1]))
				return []string{}
			}
			gist_file := strings.TrimSpace(string(matches[2]))
			fmt.Printf("Gist file: %s\n", gist_file)
			gist_content := GetGist(gist_id, gist_file)
			fmt.Printf("Gist Content: %s\n", gist_content)
			return gist_content
		}
		return []string{}
	} else if matches := hoogle.FindSubmatch([]byte(cmd)); matches != nil {
		return Hoogle(strings.Fields(string(matches[1])))
	} else if matches := man_page.FindSubmatch([]byte(cmd)); matches != nil {
		return Manpage(strings.Fields(string(matches[1])))
	}
	return []string{"Dunno what you are asking me. WTF dude?"}
}
Пример #9
0
func (l *logger) Output(v ...interface{}) {
	l.mutex.Lock()
	defer l.mutex.Unlock()
	actual := time.LocalTime()
	//l.fd.WriteString(fmt.Sprintln(actual.Year, "/", actual.Month, "/", actual.Day, " ", actual.Hour, ":", actual.Minute, ":", actual.Second, " ", v))
	l.fd.WriteString(actual.Format(time.RFC822) + " " + fmt.Sprintln(v...))
}
Пример #10
0
func (post *PostModel) Create(title string, content string) {
	t := time.LocalTime()
	err := post.c.Insert(&Post{"", title, content, t.Seconds(), 0})
	if err != nil {
		panic(err)
	}
}
Пример #11
0
// Apply offset to local time.
// Returns a Time object: http://golang.org/pkg/time/#Time
func GetFixedUpTime(o HostOffset) time.Time {
	tm := *time.LocalTime()

	switch o.Year.Op {
	case Add:
		tm.Year += int64(o.Year.Value)
	case Subtract:
		tm.Year -= int64(o.Year.Value)
	case Fix:
		tm.Year = int64(o.Year.Value)
	}

	switch o.Month.Op {
	case Add:
		tm.Month += o.Month.Value
	case Subtract:
		tm.Month -= o.Month.Value
	case Fix:
		tm.Month = o.Month.Value
	}

	switch o.Day.Op {
	case Add:
		tm.Day += o.Day.Value
	case Subtract:
		tm.Day -= o.Day.Value
	case Fix:
		tm.Day = o.Day.Value
	}

	switch o.Hour.Op {
	case Add:
		tm.Hour += o.Hour.Value
	case Subtract:
		tm.Hour -= o.Hour.Value
	case Fix:
		tm.Hour = o.Hour.Value
	}

	switch o.Minute.Op {
	case Add:
		tm.Minute += o.Minute.Value
	case Subtract:
		tm.Minute -= o.Minute.Value
	case Fix:
		tm.Minute = o.Minute.Value
	}

	switch o.Second.Op {
	case Add:
		tm.Second += o.Second.Value
	case Subtract:
		tm.Second -= o.Second.Value
	case Fix:
		tm.Second = o.Second.Value
	}

	// fmt.Println(tm.String())
	return tm
}
Пример #12
0
// This is the XMLLogWriter's output method
func (xlw *XMLLogWriter) LogWrite(rec *LogRecord) (n int, err os.Error) {
	xlw.lock.Lock()
	defer xlw.lock.Unlock()

	// First, check if we've gone over any of our rotate triggers
	if xlw.Good() {
		if (xlw.maxrecords > 0 && xlw.maxrecords_currecords >= xlw.maxrecords) ||
			(xlw.maxsize > 0 && xlw.maxsize_cursize >= xlw.maxsize) ||
			(xlw.daily && time.LocalTime().Day != xlw.daily_opendate) {
			xlw.intRotate()
		}
	}

	// Make sure the writer is (still) good
	if !xlw.Good() {
		return -1, os.NewError("File was not opened successfully")
	}

	// Perform the write
	n, err = xlw.file.Write([]byte(FormatLogRecord("\t<record level=\"%L\">\n\t\t<timestamp>%D %T</timestamp>\n\t\t<source>%S</source>\n\t\t<message>%M</message>\n\t</record>\n", rec)))

	// Update the counts
	if err == nil {
		xlw.maxrecords_currecords++
		xlw.maxsize_cursize += n
	}

	return n, err
}
Пример #13
0
// execute a request; date it, sign it, send it
func (bucket *Bucket) Execute(req *http.Request) (resp *http.Response, err os.Error) {
	// time stamp it
	date := time.LocalTime().Format(time.RFC1123)
	req.Header["Date"] = date

	// sign the request
	bucket.Sign(req)

	// open a connection
	conn, err := net.Dial("tcp", "", req.URL.Host+":"+req.URL.Scheme)
	if err != nil {
		return nil, err
	}

	// send the request
	req.Write(conn)

	// now read the response
	reader := bufio.NewReader(conn)
	resp, err = http.ReadResponse(reader, req.Method)
	if err != nil {
		return nil, err
	}

	return
}
Пример #14
0
func (acl *ApacheCombinedLogger) Log(lr *LogRecord) {
	if acl.w == nil {
		return
	}

	host, _, err := net.SplitHostPort(lr.Request.RemoteAddr)
	if err != nil {
		log.Print(fmt.Sprintf("Failed to resolve \"%s\": %s", lr.Request.RemoteAddr, err.String()))
		return
	}

	var b = &bytes.Buffer{}
	fmt.Fprintf(b, "%s - - [%s] ", host, time.LocalTime().Format(apacheTimeFormat))
	fmt.Fprintf(b, "\"%s %s HTTP/%d.%d\" ",
		lr.Request.Method, lr.Request.URL, lr.Request.ProtocolVersion/1000, lr.Request.ProtocolVersion%1000)
	fmt.Fprintf(b, "%d %d \"%s\" \"%s\"\n",
		lr.Status, lr.Written-lr.HeaderSize, lr.Request.Header.Get(web.HeaderReferer),
		lr.Request.Header.Get(web.HeaderUserAgent))

	// Lock to make sure that we don't write while log output is being changed.
	acl.mutex.Lock()
	defer acl.mutex.Unlock()

	acl.w.Write(b.Bytes())
}
Пример #15
0
// NewFileLogWriter creates a new LogWriter which writes to the given file and
// has rotation enabled if rotate is true.
//
// If rotate is true, any time a new log file is opened, the old one is renamed
// with a .### extension to preserve it.  The various Set* methods can be used
// to configure log rotation based on lines, size, and daily.
//
// The standard log-line format is:
//   [%D %T] [%L] (%S) %M
func NewFileLogWriter(fname string, rotate bool) *FileLogWriter {
	w := &FileLogWriter{
		rec:      make(chan *LogRecord, LogBufferLength),
		rot:      make(chan bool),
		filename: fname,
		format:   "[%D %T] [%L] (%S) %M",
		rotate:   rotate,
	}

	// open the file for the first time
	if err := w.intRotate(); err != nil {
		fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err)
		return nil
	}

	go func() {
		defer func() {
			if w.file != nil {
				fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Nanoseconds()}))
				w.file.Close()
			}
		}()

		for {
			select {
			case <-w.rot:
				if err := w.intRotate(); err != nil {
					fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err)
					return
				}
			case rec, ok := <-w.rec:
				if !ok {
					return
				}
				if (w.maxlines > 0 && w.maxlines_curlines >= w.maxlines) ||
					(w.maxsize > 0 && w.maxsize_cursize >= w.maxsize) ||
					(w.daily && time.LocalTime().Day != w.daily_opendate) {
					if err := w.intRotate(); err != nil {
						fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err)
						return
					}
				}

				// Perform the write
				n, err := fmt.Fprint(w.file, FormatLogRecord(w.format, rec))
				if err != nil {
					fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err)
					return
				}

				// Update the counts
				w.maxlines_curlines++
				w.maxsize_cursize += n
			}
		}
	}()

	return w
}
Пример #16
0
func log(l string) {
	// die funktion stellt die logzeie in die queue
	// erst mit der Zeit prefixen
	t := time.LocalTime()
	ts := fmt.Sprintf("%02d.%02d.%04d %02d:%02d:%02d: ",
		t.Day, t.Month, t.Year, t.Hour, t.Minute, t.Second)
	logchannel <- ts + l
}
Пример #17
0
func now() (t time.Time) {
	lt := time.LocalTime()
	t.Year = lt.Year
	t.Month = lt.Month
	t.Weekday = lt.Weekday
	t.Day = lt.Day
	return t
}
Пример #18
0
func newLogRecord(lv int, src string, msg string) *LogRecord {
	lr := new(LogRecord)
	lr.Created = time.LocalTime()
	lr.Level = lv
	lr.Source = src
	lr.Message = msg
	return lr
}
Пример #19
0
func (handler *MHandler) Clean() {
	c := handler.session.DB("bloody").C("sessions")
	t := time.LocalTime()
	err := c.RemoveAll(bson.M{"expirationts": bson.M{"$lt": t.Seconds()}})
	if err != nil {
		panic(err)
	}
}
Пример #20
0
// Yep! default formater is mandatory
// Just remember about std go formatting, which is... hmm... unique
func NewDate(format string, value ...string) *Date {
	d := &Date{format, new(time.Time), &dirtTeller{false}}
	if len(value) > 0 {
		d.Value(value[0])
	} else {
		d.value = time.LocalTime()
	}
	return d
}
Пример #21
0
func ptime(cp string) int64 {
	stm := time.LocalTime()
	sz := len(cp)

	switch {
	case sz == 11 || sz == 13 || sz == 15:
		if strings.LastIndex(cp, ".") != sz-3 {
			badtime()
		}

		stm.Second = atot(cp[sz-2:], 61)
		cp = cp[:sz-3]
		sz -= 3
		fallthrough
	case sz == 12:
		year := cp[:4]
		if stm.Year = int64(atot(year, 30000)); stm.Year < 1970 {
			badtime()
		}

		cp = cp[4:]
		sz -= 4
		fallthrough
	case sz == 10:
		var year string
		if tmp := atot(cp[:2], 99); tmp > 69 && tmp <= 99 {
			year = "19" + cp[:2]
		} else {
			year = string(2000 + int(cp[0])*10 + int(cp[1]))
		}

		stm.Year = int64(atot(year, 30000))

		cp = cp[2:]
		sz -= 2
		fallthrough
	case sz != 8:
		badtime()
	default:
		stm.Minute = atot(cp[6:], 59)
		cp = cp[:6]

		stm.Hour = atot(cp[4:], 23)
		cp = cp[:4]

		if stm.Day = atot(cp[2:], 31); stm.Day == 0 {
			badtime()
		}
		cp = cp[:2]

		if stm.Month = atot(cp, 12); stm.Month == 0 {
			badtime()
		}
	}

	return stm.Seconds()
}
Пример #22
0
func (session *Session) generateId() string {
	var header = make(http.Header)
	remoteAddr := header.Get("REMOTE_ADDR")
	t := time.LocalTime()
	var h hash.Hash = sha1.New()
	h.Write([]byte(remoteAddr + strconv.Itoa64(t.Seconds())))
	session.id = hex.EncodeToString(h.Sum())
	return session.id
}
Пример #23
0
func init() {
	servers = make([]Server, 4)
	for ind, srv := range servers {
		srv.Id = ind
		srv.DateAdded = *time.LocalTime()
		srv.Name = "NoName"
		servers[ind] = srv
	}
}
Пример #24
0
func PushServer(w http.ResponseWriter, req *http.Request) {

	var channel chan string
	var id string

	// Read the cookie,if there are any
	cookie, err := req.Cookie("stampzilla")
	if err != nil {
		//fmt.Print("No cookie\n");
	} else {
		id = cookie.Value

		//fmt.Print("Cookie: ",cookie.Value);
	}

	// Test if the channel is available
	_, test := sessions[id]

	// If channel was not found
	if id == "" || !test {
		// Create a new bufferd channel
		channel = make(chan string, 50)

		// Create a new session ID
		t := time.LocalTime()
		id = t.Format("20060102150405")

		// Save the channel
		sessions[id] = channel

	} else {
		// Select the old channel
		channel = sessions[id]
	}

	// Set the content type
	w.Header().Add("Content-Type", "text/html")

	// And add the cookie
	w.Header().Add("Set-Cookie", "stampzilla="+id)
	w.Header().Add("Expires", "Sat, 26 Jul 1997 05:00:00 GMT")
	w.Header().Add("Cache-Control", "no-cache, must-revalidate")
	w.Header().Add("Pragma", "no-cache")

	//fmt.Print("New connection ",id,", wait for data...\n");

	//fmt.Print("Querystring:"+ req.URL.RawQuery+"\n");
	//for k, val := range req.URL.Query() {
	//    fmt.Print("Query():"+ k +" - "+val[0]+"\n");
	//}
	// Start wait for data
	if req.URL.RawQuery == "start&1" {
		io.WriteString(w, "window.sape.onInit();")
	} else {
		writeToHttpFromChan(w, channel)
	}
}
Пример #25
0
func (bucket *Bucket) GetFile(file *os.FileInfo) (err os.Error) {
	url, e := http.ParseURL(bucket.Url + "/" + file.Name)
	if e != nil {
		return err
	}
	req := &http.Request{Method: "GET", RawURL: bucket.Url + "/" + file.Name, URL: url, Header: make(map[string]string)}
	date := time.LocalTime().Format(time.RFC1123)
	req.Header["Date"] = date
	bucket.sign(req)
	//req.Write(os.Stdout)

	conn, err := net.Dial("tcp", "", req.URL.Host+":"+req.URL.Scheme)
	if err != nil {
		return err
	}
	req.Write(conn)
	reader := bufio.NewReader(conn)
	resp, _ := http.ReadResponse(reader, req.Method)
	//resp.Write(os.Stdout)
	filename := strings.TrimLeft(url.Path, "/")
	path := strings.SplitAfter(filename, "/", -1)
	//pid := os.GetPid()

	var b []byte
	b, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	mode := (file.Mode & 0777)
	fmt.Printf("0%o\n", mode)
	//var dirmode uint32
	//dirmode = (syscall.S_IFDIR^0666)&0777
	resp.Body.Close()

	//create file or dir
	for i := 0; i < len(path); i++ {
		f := i + 1
		if f == len(path) {
			openfile, err := os.Open(filename, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_EXCL, mode)
			if err != nil {
				return err
			} else {
				openfile.Chown(file.Uid, file.Gid)
				openfile.Write(b)
				openfile.Close()
				os.Chtimes(filename, file.Mtime_ns, file.Mtime_ns)
			}
		} else {
			err := os.Mkdir(path[i], 0755)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
Пример #26
0
func makeManpage() {
	_, progname := path.Split(os.Args[0])
	version := Version
	if Suite != "" {
		version = Suite + " " + version
	}
	fmt.Printf(".TH \"%s\" 1 \"%s\" \"%s\" \"%s\"\n", progname,
		time.LocalTime().Format("January 2, 2006"), version, Suite)
	fmt.Println(".SH NAME")
	if Summary != "" {
		fmt.Println(progname, "\\-", Summary)
	} else {
		fmt.Println(progname)
	}
	fmt.Println(".SH SYNOPSIS")
	fmt.Println(progname, Synopsis())
	fmt.Println(".SH DESCRIPTION")
	fmt.Println(formatParagraphs(Description()))
	fmt.Println(".SH OPTIONS")
	for _, o := range opts {
		fmt.Println(".TP")
		switch {
		case len(o.shortnames) == 0:
			for _, n := range o.names[0 : len(o.names)-1] {
				fmt.Printf("\\-\\-%s,", n[2:])
			}
			fmt.Printf("\\-\\-%s", o.names[len(o.names)-1][2:])
			if o.allowsArg != nil {
				fmt.Printf(" %s", *o.allowsArg)
			}
		case len(o.names) == 0:
			for _, c := range o.shortnames[0 : len(o.shortnames)-1] {
				fmt.Printf("\\-%c,", c)
			}
			fmt.Printf("\\-%c", o.shortnames[len(o.shortnames)-1])
			if o.allowsArg != nil {
				fmt.Printf(" %s", *o.allowsArg)
			}
		default:
			for _, c := range o.shortnames {
				fmt.Printf("\\-%c,", c)
			}
			for _, n := range o.names[0 : len(o.names)-1] {
				fmt.Printf("\\-\\-%s,", n[2:])
			}
			fmt.Printf("\\-\\-%s", o.names[len(o.names)-1][2:])
			if o.allowsArg != nil {
				fmt.Printf(" %s", *o.allowsArg)
			}
		}
		fmt.Printf("\n%s\n", Expand(o.help))
	}
	if Author != "" {
		fmt.Printf(".SH AUTHOR\n%s\n", Author)
	}
}
Пример #27
0
func main() {
	log := l4g.NewLogger()
	log.AddFilter("network", l4g.FINEST, l4g.NewSocketLogWriter("udp", "192.168.1.255:12124"))

	// Run `nc -u -l -p 12124` or similar before you run this to see the following message
	log.Info("The time is now: %s", time.LocalTime().Format("15:04:05 MST 2006/01/02"))

	// This makes sure the output stream buffer is written
	log.Close()
}
Пример #28
0
func (post *PostModel) Update(title string, content string, postId string) {
	result := post.Get(postId)
	result.Title = title
	result.Content = content
	result.Modified = time.LocalTime().Seconds()
	err := post.c.Update(bson.M{"_id": bson.ObjectIdHex(postId)}, result)
	if err != nil {
		panic(err)
	}
}
Пример #29
0
func recordSighting(m *ircbot.Message) {
	s, ok := sightings[m.GetSender()]

	if !ok {
		s = make(map[string]*sighting)
		sightings[m.GetSender()] = s
	}

	s[m.Args[0]] = &sighting{time.LocalTime(), m.Trailing}
}
func main() {
	ps := os.Getpagesize()
	fmt.Println("page size = ", ps)

	sec, nsec, _ := os.Time()
	fmt.Println("time from 1 January 1970 =", sec, " secs.", nsec)

	t := time.LocalTime()
	fmt.Println(t)
}