예제 #1
0
func ParseGameState(lines []string) *PlanetWars {
	pw := &PlanetWars{make([]*Planet, len(lines)), make([]*Fleet, len(lines))}
	pNum, fNum := 0, 0

	for _, ln := range lines {

		switch ln[0] {
		case 'P':
			p := &Planet{ID: pNum}
			read, e := fmt.Sscanf(ln[2:], "%f %f %d %d %d", &p.X, &p.Y, &p.Owner, &p.NumShips, &p.GrowthRate)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Planets[pNum] = p
			pNum++
		case 'F':
			f := &Fleet{ID: fNum}
			read, e := fmt.Sscanf(ln[2:], "%d %d %d %d %d", &f.Owner, &f.NumShips, &f.Source, &f.Dest, &f.TripLength, &f.TurnsRemaining)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Fleets[fNum] = f
			fNum++
		default:
			log.Stderr("Error parsing gamestate: First char of line not 'P' or 'F'\n")
			return nil
		}
	}

	pw.Fleets = pw.Fleets[0:fNum]
	pw.Planets = pw.Planets[0:pNum]
	return pw
}
예제 #2
0
func main() {
	flag.Parse()
	if len(*deliciousUser) == 0 || len(*deliciousPassword) == 0 {
		log.Stderrf("Missing user or password.\n\n")
		flag.Usage()
		os.Exit(2)
	}
	if strings.HasPrefix(*deliciousUrl, "http://") != true {
		log.Stderrf("URL missing 'http://' prefix. HTTPS is currently NOT supported.\n\n")
		flag.Usage()
		os.Exit(2)
	}
	userInfo := strings.Split(*deliciousUrl, "http://", 2)[1]
	url := fmt.Sprintf("http://%s:%s@%s", *deliciousUser, *deliciousPassword, userInfo)

	b, err := readData(url)
	if err != nil {
		log.Stderrf("Error downloading %s: %s", url, err)
		os.Exit(1)
	}
	err = saveBackup(b)
	if err != nil {
		log.Stderrf("Error saving file to disk %s", err)
		os.Exit(1)
	}
}
예제 #3
0
// getPageInfo returns the PageInfo for a package directory path. If the
// parameter try is true, no errors are logged if getPageInfo fails.
// If there is no corresponding package in the directory,
// PageInfo.PDoc is nil. If there are no subdirectories,
// PageInfo.Dirs is nil.
//
func (h *httpHandler) getPageInfo(path string, try bool) PageInfo {
	// the path is relative to h.fsroot
	dirname := pathutil.Join(h.fsRoot, path)

	// the package name is the directory name within its parent
	// (use dirname instead of path because dirname is clean; i.e. has no trailing '/')
	_, pkgname := pathutil.Split(dirname)

	// filter function to select the desired .go files
	filter := func(d *os.Dir) bool {
		if isPkgFile(d) {
			// Some directories contain main packages: Only accept
			// files that belong to the expected package so that
			// parser.ParsePackage doesn't return "multiple packages
			// found" errors.
			// Additionally, accept the special package name
			// fakePkgName if we are looking at cmd documentation.
			name := pkgName(dirname + "/" + d.Name)
			return name == pkgname || h.fsRoot == *cmdroot && name == fakePkgName
		}
		return false
	}

	// get package AST
	pkgs, err := parser.ParseDir(dirname, filter, parser.ParseComments)
	if err != nil && !try {
		// TODO: errors should be shown instead of an empty directory
		log.Stderrf("parser.parseDir: %s", err)
	}
	if len(pkgs) != 1 && !try {
		// TODO: should handle multiple packages
		log.Stderrf("parser.parseDir: found %d packages", len(pkgs))
	}
	var pkg *ast.Package
	for _, pkg = range pkgs {
		break // take the first package found
	}

	// compute package documentation
	var pdoc *doc.PackageDoc
	if pkg != nil {
		ast.PackageExports(pkg)
		pdoc = doc.NewPackageDoc(pkg, pathutil.Clean(path)) // no trailing '/' in importpath
	}

	// get directory information
	var dir *Directory
	if tree, _ := fsTree.get(); tree != nil {
		// directory tree is present; lookup respective directory
		// (may still fail if the file system was updated and the
		// new directory tree has not yet beet computed)
		dir = tree.(*Directory).lookup(dirname)
	} else {
		// no directory tree present (either early after startup
		// or command-line mode); compute one level for this page
		dir = newDirectory(dirname, 1)
	}

	return PageInfo{pdoc, dir.listing(true), h.isPkg}
}
예제 #4
0
// TODO: need uuid for session
// TODO: cookie domain site param?
// TODO: cookie exparation
func DEFAULT(c *http.Conn, req *http.Request) {
	s := session_service.GetSession(c,req);
	log.Stderrf("session data id:%s", s.Id);
	for k,v := range s.Data {
		log.Stderrf("session kv:%s:%s", k, v);
	}
	var defaultTemplate = get_template("default.html");
	defaultTemplate.Execute(s.Id, c);
}
예제 #5
0
파일: model.go 프로젝트: nono/Goldorak.Go
func (this *Model) Create(param string) *Instance {
	p := Parameterize(param)
	id, err := this.NextId()
	if err != nil {
		log.Stderrf("Impossible to create an instance of %s", this.name, err)
		return nil
	}
	err = this.Set(p, string(id))
	if err != nil {
		log.Stderrf("Impossible to create an instance of %s", this.name, err)
		return nil
	}
	return &Instance{this, id, p}
}
예제 #6
0
// TODO: malicious ids
func (ps *PersistService) Get(id string) (*Model, bool) {
	log.Stderrf("PS:GET:%s", id);
	mpath := path.Join(ps.Path, id);
	log.Stderrf("PS:GET:path:%s", mpath);
	bs, e := io.ReadFile(mpath);
	// TODO: check error more specifically (not found, etc.)
	if e != nil {
		log.Stderrf("PS:GET:e:%s", e);
		return nil, false;
	}
	else {
		return parse_model(id, bs), true;
	}
	panic("unreachable");
}
예제 #7
0
func (ps *PersistService) Del(id string) os.Error {
	// TODO: malicious id path
	log.Stderrf(":DEL:id:%s", id);
	mpath := path.Join(ps.Path, id);
	e := os.Remove(mpath);
	return e;
}
예제 #8
0
func (l *listenConn) run() {
	log.Stderrf("listening on %s\n", l.listen.Addr())
	// TODO a way to shut this down
	for {
		conn, err := l.listen.Accept()
		if err != nil {
			log.Stderrf("accept failed: %s\n", err)
			l.listen.Close()
			if l.error != nil {
				l.error(err)
			}
			return
		}
		l.accept(conn)
	}
}
예제 #9
0
파일: godoc.go 프로젝트: ivanwyc/google-go
func applyTemplate(t *template.Template, name string, data interface{}) []byte {
	var buf bytes.Buffer
	if err := t.Execute(data, &buf); err != nil {
		log.Stderrf("%s.Execute: %s", name, err)
	}
	return buf.Bytes()
}
예제 #10
0
파일: db.go 프로젝트: fedgrant/tonika
// Saves the database to the friend db file that was used to read it
// TODO: This should be checkpointed to prevent data loss
func (db *buttress) Save() os.Error {
	// Convert to json
	me := db.me
	jm := jsonMe{
		Id:      me.Id.String(),
		SigKey:  me.SignatureKey.String(),
		Name:    me.Name,
		Email:   me.Email,
		Addr:    me.Addr,
		ExtAddr: me.ExtAddr,
	}
	book := &jsonDb{jm, make([]jsonFriend, len(db.recs))}
	k := 0
	for _, v := range db.recs {
		jf := jsonFriend{
			Slot:  strconv.Itoa(v.Slot),
			Name:  v.Name,
			Email: v.Email,
			Addr:  v.Addr,
			Rest:  v.Rest,
		}
		if v.Id != nil {
			jf.Id = v.Id.String()
		}
		if v.SignatureKey != nil {
			jf.SigKey = v.SignatureKey.String()
		}
		if v.HelloKey != nil {
			jf.HelloKey = v.HelloKey.String()
		}
		if v.DialKey != nil {
			jf.DialKey = v.DialKey.String()
		}
		if v.AcceptKey != nil {
			jf.AcceptKey = v.AcceptKey.String()
		}
		book.Friends[k] = jf
		k++
	}
	// Open file
	file, err := os.Open(db.path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Stderrf("Cannot open friends file \"%s\"\n", db.path)
		return &Error{ErrSave, err}
	}
	// Marshal to json string
	data, err := json.Marshal(&book)
	if err != nil {
		return &Error{ErrEncode, err}
	}
	bf := bytes.NewBuffer(data)
	n, err := io.Copy(file, bf)
	if err != nil || n != int64(len(data)) {
		return &Error{ErrEncode, err}
	}
	if err := file.Close(); err != nil {
		return &Error{ErrSave, err}
	}
	return nil
}
예제 #11
0
func readOb(s net.Conn, buf []byte) {
	x, err := io.ReadFull(s, buf)
	if err != nil || x != len(buf) {
		log.Stderrf("Error reading part: %s", err)
		runtime.Goexit()
	}
}
예제 #12
0
파일: scgi.go 프로젝트: sschober/web.go
func handleScgiRequest(fd io.ReadWriteCloser) {
	var buf bytes.Buffer
	var tmp [1024]byte
	n, err := fd.Read(&tmp)
	if err != nil || n == 0 {
		return
	}

	colonPos := bytes.IndexByte(tmp[0:], ':')

	read := n
	length, _ := strconv.Atoi(string(tmp[0:colonPos]))
	buf.Write(tmp[0:n])

	for read < length {
		n, err := fd.Read(&tmp)
		if err != nil || n == 0 {
			break
		}

		buf.Write(tmp[0:n])
		read += n
	}

	req, err := readScgiRequest(&buf)

	if err != nil {
		log.Stderrf("SCGI read error", err.String())
		return
	}

	sc := scgiConn{fd, make(map[string][]string), false}
	routeHandler(req, &sc)
	fd.Close()
}
예제 #13
0
func TestServerClient(t *testing.T) {
	port := empty_port()
	ok(t, port != 0, "empty_port")
	log.Stderrf("got empty port: %d", port)

	addr := fmt.Sprintf("localhost:%d", port)
	go RunServer(addr)

	time.Sleep(int64(1) * 1e8) // wait for Server started

	client, err := NewClient(addr)
	ok(t, err == nil, "NewClient()")

	var value string
	value, err = client.Get("xxx")
	ok(t, err == nil, "")
	ok(t, value == "", "client.Get(xxx) == \"\"")

	for i := 0; i < 10; i++ {
		key := fmt.Sprintf("key_%d", i)
		val := fmt.Sprintf("val_%d", i)

		_, err = client.Set(key, val)
		ok(t, err == nil, fmt.Sprintf("client.Set(%s,%s)", key, val))

		value, err = client.Get(key)
		ok(t, err == nil, "")
		ok(t, value == val, fmt.Sprintf("client.Get(%s)", key))
	}
}
예제 #14
0
파일: model.go 프로젝트: nono/Goldorak.Go
func (this *Model) Find(param string) *Instance {
	value, err := this.Get(param)
	if err != nil {
		log.Stderrf("Impossible to find %s (%s)", param, this.name, err)
		return nil
	}
	if value == "" {
		return nil
	}
	id, err := strconv.Atoi64(value)
	if err != nil {
		log.Stderrf("Impossible to convert %s to int", value, err)
		return nil
	}
	return &Instance{this, id, param}
}
예제 #15
0
func search(c *http.Conn, r *http.Request) {
	query := strings.TrimSpace(r.FormValue("q"))
	var result SearchResult

	if index, timestamp := searchIndex.get(); index != nil {
		result.Query = query
		result.Hit, result.Alt, result.Illegal = index.(*Index).Lookup(query)
		_, ts := fsTree.get()
		result.Accurate = timestamp >= ts
	}

	var buf bytes.Buffer
	if err := searchHTML.Execute(result, &buf); err != nil {
		log.Stderrf("searchHTML.Execute: %s", err)
	}

	var title string
	if result.Hit != nil {
		title = fmt.Sprintf(`Results for query %q`, query)
	} else {
		title = fmt.Sprintf(`No results found for query %q`, query)
	}

	servePage(c, title, query, buf.Bytes())
}
예제 #16
0
func serveHTMLDoc(c *http.Conn, r *http.Request, path string) {
	// get HTML body contents
	src, err := ioutil.ReadFile(path)
	if err != nil {
		log.Stderrf("%v", err)
		http.NotFound(c, r)
		return
	}

	// if it begins with "<!DOCTYPE " assume it is standalone
	// html that doesn't need the template wrapping.
	if bytes.HasPrefix(src, strings.Bytes("<!DOCTYPE ")) {
		c.Write(src)
		return
	}

	// if it's the language spec, add tags to EBNF productions
	if strings.HasSuffix(path, "go_spec.html") {
		var buf bytes.Buffer
		linkify(&buf, src)
		src = buf.Bytes()
	}

	title := commentText(src)
	servePage(c, title, "", src)
}
예제 #17
0
파일: fcgi.go 프로젝트: iamnafets/web.go
func (s *Server) listenAndServeFcgi(addr string) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Stderrf("FCGI listen error", err.String())
		return
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			log.Stderrf("FCGI accept error", err.String())
			break
		}
		go s.handleFcgiConnection(fd)
	}
}
예제 #18
0
func parse_model(id string, bs []byte) *Model {
	log.Stderrf("PS:parse_model:%s:%s", id, bs);
	data := parse_model_data(bs);
	m := new(Model);
	m.Id = id;
	m.Data = data;
	return m;
}
예제 #19
0
파일: model.go 프로젝트: nono/Goldorak.Go
func (this *Instance) Get(field string) string {
	value, err := this.model.Get(this.FieldKey(field))
	if err != nil {
		log.Stderrf("Impossible to get %s", field, err)
		return ""
	}
	return value
}
예제 #20
0
func (player *Player) PacketDisconnect(reason string) {
	log.Stderrf("PacketDisconnect reason=%s", reason)
	player.game.Enqueue(func(game *Game) {
		game.RemovePlayer(player)
		close(player.txQueue)
		player.conn.Close()
	})
}
예제 #21
0
func (c *AuthClient) get_auth_token(callback_url string) *persist.Model { // *AuthToken {
	r, finalUrl, err := c.MakeRequest(c.request_url, map[string]string{"oauth_callback":callback_url}, "", false);
	if r != nil {
		log.Stderrf("get_auth_token:status:%s:finalUrl:%s", r.Status, finalUrl);
		for k, v := range r.Header {
			log.Stderrf("header:%s:%s", k, v);
		}
	}
	else {
		log.Stderrf("get_auth_token:finalUrl:%s:err:%s", finalUrl, err.String());
	}

	kvmap := parse_response(r); // check for 503
	// oauth_callback_confirmed=true assert?
	token := create_auth_token( c.persist_service, kvmap["oauth_token"], kvmap["oauth_token_secret"] );
	return token;
}
예제 #22
0
func handleFlush(req MCRequest, s *storage) (ret MCResponse) {
	delay := ReadUint32(req.Extras, 0)
	if delay > 0 {
		log.Stderrf("Delay not supported (got %d)", delay)
	}
	s.data = make(map[string]MCItem)
	return
}
예제 #23
0
파일: scgi.go 프로젝트: tjweir/web.go
func listenAndServeScgi(addr string) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Stderrf(err.String())
		return
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			log.Stderrf(err.String())
			break
		}
		go handleScgiRequest(fd)

	}
}
예제 #24
0
// TODO: all
func (c *AuthClient) GetUserInfo(auth_token string, auth_verifier string) map[string]string {
	// get secret
	auth_secret := get_auth_secret(c.persist_service, auth_token);
	log.Stderrf("AUTH_SECRET:%s", auth_secret); // should client error if not found
	r, finalUrl, err := c.MakeRequest(c.access_url, map[string]string{"oauth_token":auth_token, "oauth_verifier":auth_verifier}, auth_secret, false);
	if r != nil {
		log.Stderrf("get_access_token:status:%s:finalUrl:%s", r.Status, finalUrl);
		for k, v := range r.Header {
			log.Stderrf("header:%s:%s", k, v);
		}
	}
	else {
		log.Stderrf("get_access_token:finalUrl:%s:err:%s", finalUrl, err.String());
	}
	kvmap := parse_response(r); // check for 503
	return kvmap;
}
예제 #25
0
파일: godoc.go 프로젝트: 8l/go-learn
func serveParseErrors(c *http.Conn, errors *parseErrors) {
	// format errors
	var buf bytes.Buffer
	if err := parseerrorHtml.Execute(errors, &buf); err != nil {
		log.Stderrf("parseerrorHtml.Execute: %s", err)
	}
	servePage(c, "Parse errors in source file "+errors.filename, "", buf.Bytes())
}
예제 #26
0
// receives ?returnto=/replies etc.
func CALLBACK(c *http.Conn, req *http.Request, auth_client *oauth.AuthClient) {
	log.Stderr("CALLBACK!");
	req.ParseForm();
	for k,v := range req.Header {
		log.Stderrf("header:%s:%s", k, v);
	}
	for k,vs := range req.Form {
		log.Stderrf("form:%s::", k);
		for i := range vs {
			log.Stderrf("::%s", vs[i]);
		}
	}

	var auth_token = req.FormValue("oauth_token");
	var auth_verifier = req.FormValue("oauth_verifier");
	log.Stderrf("CALLBACK:auth_token:%s:", auth_token);
	log.Stderrf("CALLBACK:auth_verifier:%s:", auth_verifier);

	user_info := auth_client.GetUserInfo(auth_token, auth_verifier);

	log.Stderrf("USER_INFO:");
	for k,v := range user_info {
		log.Stderrf("k:%s v:%s", k, v);
	}

	session_service.StartSession(c, req, user_info);
	var url = "/";
	returnto := req.FormValue("returnto");
	if returnto != "" {
		url = returnto;
	}
	http.Redirect(c, url, http.StatusFound); // should be 303 instead of 302?
}
예제 #27
0
파일: main.go 프로젝트: 8l/go-learn
func exec(c *http.Conn, args []string) (status int) {
	r, w, err := os.Pipe();
	if err != nil {
		log.Stderrf("os.Pipe(): %v\n", err);
		return 2;
	}

	bin := args[0];
	fds := []*os.File{nil, w, w};
	if *verbose {
		log.Stderrf("executing %v", args);
	}
	pid, err := os.ForkExec(bin, args, os.Environ(), goroot, fds);
	defer r.Close();
	w.Close();
	if err != nil {
		log.Stderrf("os.ForkExec(%q): %v\n", bin, err);
		return 2;
	}

	var buf bytes.Buffer;
	io.Copy(&buf, r);
	wait, err := os.Wait(pid, 0);
	if err != nil {
		os.Stderr.Write(buf.Bytes());
		log.Stderrf("os.Wait(%d, 0): %v\n", pid, err);
		return 2;
	}
	status = wait.ExitStatus();
	if !wait.Exited() || status > 1 {
		os.Stderr.Write(buf.Bytes());
		log.Stderrf("executing %v failed (exit status = %d)", args, status);
		return;
	}

	if *verbose {
		os.Stderr.Write(buf.Bytes());
	}
	if c != nil {
		c.SetHeader("content-type", "text/plain; charset=utf-8");
		c.Write(buf.Bytes());
	}

	return;
}
예제 #28
0
파일: web.go 프로젝트: surapaneni/web.go
func addRoute(r string, method string, handler interface{}) {
	cr, err := regexp.Compile(r)
	if err != nil {
		log.Stderrf("Error in route regex %q\n", r)
		return
	}
	fv := reflect.NewValue(handler).(*reflect.FuncValue)
	routes.Push(route{r, cr, method, fv})
}
예제 #29
0
func RunServer(input chan MCRequest) {
	var s storage
	s.data = make(map[string]MCItem)
	for {
		req := <-input
		log.Stderrf("Got a request: %s", req)
		req.ResponseChannel <- dispatch(req, &s)
	}
}
예제 #30
0
파일: fcgi.go 프로젝트: tjweir/web.go
func listenAndServeFcgi(addr string) {
	println("listening and serving scgi!")
	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Stderrf(err.String())
		return
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			log.Stderrf(err.String())
			break
		}
		go handleFcgiRequest(fd)

	}
}