Exemplo n.º 1
1
// Symbol looks up the program counters listed in the request,
// responding with a table mapping program counters to function names.
// The package initialization registers it as /debug/pprof/symbol.
func Symbol(c *http.Conn, r *http.Request) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")

	// We don't know how many symbols we have, but we
	// do have symbol information.  Pprof only cares whether
	// this number is 0 (no symbols available) or > 0.
	fmt.Fprintf(c, "num_symbols: 1\n")

	var b *bufio.Reader
	if r.Method == "POST" {
		b = bufio.NewReader(r.Body)
	} else {
		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
	}

	for {
		w, err := b.ReadSlice('+')
		if err == nil {
			w = w[0 : len(w)-1] // trim +
		}
		pc, _ := strconv.Btoui64(string(w), 0)
		if pc != 0 {
			f := runtime.FuncForPC(uintptr(pc))
			if f != nil {
				fmt.Fprintf(c, "%#x %s\n", pc, f.Name())
			}
		}

		// Wait until here to check for err; the last
		// symbol will have an err because it doesn't end in +.
		if err != nil {
			break
		}
	}
}
Exemplo n.º 2
0
func TWITTER_REPLIES(c *http.Conn, req *http.Request) {
	log.Stderrf(">REPLIES:");
	s := session_service.GetSession(c,req);
	for k,v := range s.Data {
		log.Stderrf("session kv:%s:%s", k, v);
	}
	auth_token, atx := s.Data["oauth_token"];
	if atx {
		log.Stderrf("TOKEN FOUND!");
		auth_token_secret := s.Data["oauth_token_secret"];
		r, finalUrl, err := twitter_client.MakeRequest("http://twitter.com/statuses/mentions.json", map[string]string{"oauth_token":auth_token}, auth_token_secret, false); //{"since_id":s.last_reply_id})
		if err != nil {
			log.Stderrf(":REPLIES:err:%s",err);
		}
		else {
			log.Stderrf(":REPLIES:r:%s:finalUrl:%s", r, finalUrl);
			b, _ := io.ReadAll(r.Body);
			print ("REPLIES!");
			str := bytes.NewBuffer(b).String();
       			println (str);
			j, ok, errtok := json.StringToJson(str);
			log.Stderr("REPLIES:j:%s:ok:%s:errtok:%s", j, ok, errtok);
			c.Write(strings.Bytes(j.String()));
		}
	
	}
	else {
		log.Stderrf("NO TOKEN FOUND!");
		http.Redirect(c, "/login/twitter?returnto=/twitter/replies", http.StatusFound); // should be 303 instead of 302?
	}
}
Exemplo n.º 3
0
// exec a program, redirecting output
func DateServer(c *http.Conn, req *http.Request) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")
	r, w, err := os.Pipe()
	if err != nil {
		fmt.Fprintf(c, "pipe: %s\n", err)
		return
	}
	pid, err := os.ForkExec("/bin/date", []string{"date"}, os.Environ(), "", []*os.File{nil, w, w})
	defer r.Close()
	w.Close()
	if err != nil {
		fmt.Fprintf(c, "fork/exec: %s\n", err)
		return
	}
	io.Copy(c, r)
	wait, err := os.Wait(pid, 0)
	if err != nil {
		fmt.Fprintf(c, "wait: %s\n", err)
		return
	}
	if !wait.Exited() || wait.ExitStatus() != 0 {
		fmt.Fprintf(c, "date: %v\n", wait)
		return
	}
}
Exemplo n.º 4
0
func Send(c *http.Conn, req *http.Request) {
	query_params, _ := http.ParseQuery(req.URL.RawQuery)
	arg_game, ok_game := query_params["game"]
	arg_msg, ok_msg := query_params["msg"]
	if !ok_game {
		c.Write([]byte("Game parameter not set"))
		return
	}
	if !ok_msg {
		c.Write([]byte("Msg parameter not set"))
		return
	}
	game := arg_game[0]
	msg := arg_msg[0]
	params := strings.Split(game, ",", 2)
	if len(params) != 2 {
		c.Write([]byte("Malformed game parameter"))
		return
	}
	game_id, player_id := params[0], params[1]
	game_instance := room.Find(game_id)
	if room == nil {
		c.Write([]byte("Game not found"))
		return
	}
	result := game_instance.Send(player_id, msg)
	c.Write([]byte(result))
}
Exemplo n.º 5
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)
}
Exemplo n.º 6
0
Arquivo: views.go Projeto: tung/goblog
// url: /blog/entry/add
func AddEntry(c *http.Conn, req *http.Request) {
	req.ParseForm();
	heading, body := req.FormValue("heading"), req.FormValue("body");
	if len(heading) > 0 && len(body) > 0 {
		blog.AddEntry(heading, body)
	}
	c.SetHeader("Location", "/blog");
	c.WriteHeader(http.StatusFound);
}
Exemplo n.º 7
0
func (s *Swif) handleError(code int, c *http.Conn) {
	switch code {
	case http.StatusBadRequest:
		c.WriteHeader(code)
		io.WriteString(c, "Invalid Request")
	default:
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "Invalid Request")
	}
}
Exemplo n.º 8
0
// hello world, the web server
func HelloServer(c *http.Conn, req *http.Request)
{
  var creq CRequest;
  creq.conn = c;
  creq.req = req;
  //fmt.Printf("%s\n", creq.req);
  var e os.Error;
  creq.rwc, creq.buf, e = c.Hijack();
  if (e!=nil) {}
  req_channel <- creq;
}
Exemplo n.º 9
0
func FlagServer(c *http.Conn, req *http.Request) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")
	fmt.Fprint(c, "Flags:\n")
	flag.VisitAll(func(f *flag.Flag) {
		if f.Value.String() != f.DefValue {
			fmt.Fprintf(c, "%s = %s [default = %s]\n", f.Name, f.Value.String(), f.DefValue)
		} else {
			fmt.Fprintf(c, "%s = %s\n", f.Name, f.Value.String())
		}
	})
}
Exemplo n.º 10
0
func (s FileServer) ServeHTTP(c *http.Conn, req *http.Request) {
	content, err := ioutil.ReadFile(s.loc)
	if err != nil {
		log.Stderr(err)
	} else {
		// get mime type
		mimeType := mime.TypeByExtension(path.Ext(s.loc)) // TODO cache this
		c.SetHeader("Content-Type", mimeType)
		fmt.Fprintf(c, "%s", content)
	}
}
Exemplo n.º 11
0
func TestCode2(c *http.Conn, req *http.Request) {
	dump, err := http.DumpRequest(req, true)
	if err != nil {
		io.WriteString(c, err.String())
		return
	}
	_, err = c.Write(dump)
	if err != nil {
		io.WriteString(c, err.String())
		return
	}
	log.Stdout(string(dump))
}
Exemplo n.º 12
0
func Wait(c *http.Conn, req *http.Request) {
	query_params, _ := http.ParseQuery(req.URL.RawQuery)
	arg_owner_id, ok_owner_id := query_params["owner_id"]
	if ok_owner_id {
		fmt.Println("Create owner_id=", arg_owner_id)
		owner_id := arg_owner_id[0]
		game_id := room.Wait(owner_id)
		fmt.Println("Create ", game_id)
		c.Write([]byte(game_id))
	} else {
		c.Write([]byte("Parameters not specified correctly"))
	}
}
Exemplo n.º 13
0
func Connect(c *http.Conn, req *http.Request) {
	query_params, _ := http.ParseQuery(req.URL.RawQuery)
	arg_owner, ok_owner := query_params["owner"]
	if ok_owner {
		fmt.Println("Connect owner=", arg_owner)
		owner := arg_owner[0]
		owner_id := room.Connect(owner)
		fmt.Println("Connected as ", owner_id)
		c.Write([]byte(owner_id))
	} else {
		c.Write([]byte("Parameters not specified correctly"))
	}
}
Exemplo n.º 14
0
func expvarHandler(c *http.Conn, req *http.Request) {
	c.SetHeader("content-type", "application/json; charset=utf-8")
	fmt.Fprintf(c, "{\n")
	first := true
	for name, value := range vars {
		if !first {
			fmt.Fprintf(c, ",\n")
		}
		first = false
		fmt.Fprintf(c, "%q: %s", name, value)
	}
	fmt.Fprintf(c, "\n}\n")
}
Exemplo n.º 15
0
Arquivo: views.go Projeto: tung/goblog
// url: /blog/comment/add
func AddComment(c *http.Conn, req *http.Request) {
	req.ParseForm();
	entryIDString, text := req.FormValue("entry_id"), req.FormValue("text");
	if len(entryIDString) > 0 && len(text) > 0 {
		if entryID, parseErr := strconv.Atoi(entryIDString); parseErr == nil {
			if foundEntry := blog.FindEntry(entryID); foundEntry != nil {
				foundEntry.AddComment(text);
			}
		}
	}
	c.SetHeader("Location", "/blog/entry/" + entryIDString);
	c.WriteHeader(http.StatusFound);
}
Exemplo n.º 16
0
func (ss *SessionService) StartSession(c *http.Conn, req *http.Request, d map[string]string) *persist.Model { // d was json.Json
	log.Stderrf(">StartSession:");
	// TODO: uuid4 generate sid instead of "sid-" plus random
	// s := new(Session);
	// s.Id = ss.Name + "-" + strconv.Itoa(rand.Int());
	// s.Data = d;
	s := ss.persist_service.New(ss.Name+"-"+strconv.Itoa(rand.Int()), d);
	// TODO: refactor out cookie things
	// TODO: cookie domain
	c.SetHeader("Set-Cookie", ss.Name+"=" + s.Id + "; expires=Fri, 31-Dec-2011 23:59:59 GMT; path=/; domain=sol.caveman.org");
	// TODO: real thing not unprotected (threadwise) in-memory only "sessions"
	// ss.sessions[s.Id] = *s;
	return s;
}
Exemplo n.º 17
0
// ServeHTTP implements the http.Handler interface for a Web Socket.
func (f Draft75Handler) ServeHTTP(c *http.Conn, req *http.Request) {
	if req.Method != "GET" || req.Proto != "HTTP/1.1" {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "Unexpected request")
		return
	}
	if req.Header["Upgrade"] != "WebSocket" {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "missing Upgrade: WebSocket header")
		return
	}
	if req.Header["Connection"] != "Upgrade" {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "missing Connection: Upgrade header")
		return
	}
	origin, found := req.Header["Origin"]
	if !found {
		c.WriteHeader(http.StatusBadRequest)
		io.WriteString(c, "missing Origin header")
		return
	}

	rwc, buf, err := c.Hijack()
	if err != nil {
		panic("Hijack failed: " + err.String())
		return
	}
	defer rwc.Close()
	location := "ws://" + req.Host + req.URL.RawPath

	// TODO(ukai): verify origin,location,protocol.

	buf.WriteString("HTTP/1.1 101 Web Socket Protocol Handshake\r\n")
	buf.WriteString("Upgrade: WebSocket\r\n")
	buf.WriteString("Connection: Upgrade\r\n")
	buf.WriteString("WebSocket-Origin: " + origin + "\r\n")
	buf.WriteString("WebSocket-Location: " + location + "\r\n")
	protocol, found := req.Header["Websocket-Protocol"]
	// canonical header key of WebSocket-Protocol.
	if found {
		buf.WriteString("WebSocket-Protocol: " + protocol + "\r\n")
	}
	buf.WriteString("\r\n")
	if err := buf.Flush(); err != nil {
		return
	}
	ws := newConn(origin, location, protocol, buf, rwc)
	f(ws)
}
Exemplo n.º 18
0
func serveError502(conn *http.Conn, host string) {
	conn.WriteHeader(http.StatusBadGateway)
	conn.SetHeader(contentType, textHTML)
	conn.SetHeader(contentLength, error502Length)
	conn.Write(error502)
	logRequest(http.StatusBadGateway, host, conn)
}
Exemplo n.º 19
0
func FileServer(c *http.Conn, req *http.Request) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")
	pathVar.Add(req.URL.Path, 1)
	path := *webroot + req.URL.Path // TODO: insecure: use os.CleanName
	f, err := os.Open(path, os.O_RDONLY, 0)
	if err != nil {
		c.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(c, "open %s: %v\n", path, err)
		return
	}
	n, _ := io.Copy(c, f)
	fmt.Fprintf(c, "[%d bytes]\n", n)
	f.Close()
}
Exemplo n.º 20
0
func home(c *http.Conn, req *http.Request) {
	if req.Method == "POST" && len(strings.TrimSpace(req.FormValue("code"))) > 0 {
		paste := savePaste(req.FormValue("code"), req.FormValue("private") != "")
		c.SetHeader("Content-type", "text/plain; charset=utf-8")
		c.Write(strings.Bytes("http://" + DOMAIN + "/view/" + paste + "\n"))
	} else {
		theme := curTheme(req)
		homePage.Execute(map[string]string{
			"theme":        theme,
			"theme_select": themeSelect(theme),
		},
			c)
	}
}
Exemplo n.º 21
0
func handlePngChart(c *http.Conn, req *http.Request) {
	// Fehlerhandler registrieren
	defer handleErrors("handlePngChart", true)
	log("Erzeuge PNG Chart...")
	// CSV-Datei einlesen
	data, err := readCsvFile("./table.csv")
	if err == nil {
		// Content-Type im HTTP-Header
		c.SetHeader("Content-Type", "image/png")
		// Chart erzeugen und in den Ausgabestrom schreiben
		drawPngChart(600, 400, data, c)
		log("PNG Chart ausgeliefert.")
	} else {
		log("PNG Chart konnte nicht erstellt werden.")
	}
}
Exemplo n.º 22
0
Arquivo: views.go Projeto: tung/goblog
// url: /blog
func Index(c *http.Conn, req *http.Request) {
	revEntries := blog.EntriesReversed();
	frontPageEntries := make([]frontPageEntry, len(revEntries));
	for i, e := range revEntries {
		frontPageEntries[i].Entry = e;
		frontPageEntries[i].CommentCount = e.Comments.Len();
	}

	if tmpl, err := loadTemplate("index.html"); err == nil {
		tmpl.Execute(frontPageEntries, c);
	} else {
		c.SetHeader("Content-Type", "text/plain; charset=utf-8");
		c.WriteHeader(http.StatusInternalServerError);
		io.WriteString(c, "500 internal server error\n");
	}
}
Exemplo n.º 23
0
Arquivo: main.go Projeto: 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;
}
Exemplo n.º 24
0
func (r *Robot) ServeHTTP(conn *http.Conn, req *http.Request) {
	log("Path:", req.URL.Path)
	switch req.URL.Path {
	case r.pathPrefix + "/robot/jsonrpc":
		// decode request bundle
		body, _ := ioutil.ReadAll(req.Body)
		logf("Request:\n%s\n\n", body)
		b := new(requestBundle)
		err := json.Unmarshal(body, b)
		if err != nil {
			http.Error(conn, "Bad request", http.StatusBadRequest)
			return
		}

		oq := NewOperationQueue()
		w := NewWavelet(b.Wavelet, b.Blips, r, oq)

		// handle events
		for _, e := range b.Events {
			if handler, ok := r.handlers[e.Type]; ok {
				handler(e, w)
			}
		}

		// output operation queue
		q, _ := json.Marshal(oq.pending)
		logf("Response:\n%s\n\n", q)
		conn.Write(q)
	case r.pathPrefix + "/capabilities.xml":
		fmt.Fprintf(conn, capabilitiesXMLstart, r.version())
		for k, _ := range r.handlers {
			fmt.Fprintf(conn, capabilityXML, k)
		}
		fmt.Fprint(conn, capabilitiesXMLend)
	case r.pathPrefix + "/robot/profile":
		p, _ := json.Marshal(map[string]string{
			"profileUrl": r.profileUrl,
			"imageUrl":   r.imageUrl,
			"name":       r.name,
		})
		conn.Write(p)
	default:
		http.NotFound(conn, req)
	}
}
Exemplo n.º 25
0
func (redirector *Redirector) ServeHTTP(conn *http.Conn, req *http.Request) {

	var url string
	if len(req.URL.RawQuery) > 0 {
		url = fmt.Sprintf(redirectURLQuery, redirector.url, req.URL.Path, req.URL.RawQuery)
	} else {
		url = fmt.Sprintf(redirectURL, redirector.url, req.URL.Path)
	}

	if len(url) == 0 {
		url = "/"
	}

	conn.SetHeader("Location", url)
	conn.WriteHeader(http.StatusMovedPermanently)
	fmt.Fprintf(conn, redirectHTML, url)
	logRequest(http.StatusMovedPermanently, req.Host, conn)

}
Exemplo n.º 26
0
Arquivo: web.go Projeto: tjweir/web.go
func httpHandler(c *http.Conn, req *http.Request) {
	path := req.URL.Path

	//try to serve a static file
	if strings.HasPrefix(path, "/static/") {
		staticFile := path[8:]
		if len(staticFile) > 0 {
			http.ServeFile(c, req, "static/"+staticFile)
			return
		}
	}

	req.ParseForm()
	resp := routeHandler((*Request)(req))
	c.WriteHeader(resp.StatusCode)
	if resp.Body != nil {
		body, _ := ioutil.ReadAll(resp.Body)
		c.Write(body)
	}
}
Exemplo n.º 27
0
func (this *router) ServeHTTP(conn *http.Conn, httpReq *http.Request) {
	var reqs []*Request
	contentType := httpReq.Header["Content-Type"]
	switch {
	default:
		http.Error(conn, fmt.Sprintf("Illegal content type %v", contentType), http.StatusInternalServerError)
		return
	case strings.HasPrefix(contentType, "application/json"):
		reqs = this.decodeTransaction(httpReq.Body)
	case strings.HasPrefix(contentType, "application/x-www-form-urlencoded"):
		httpReq.ParseForm()
		reqs = this.decodeFormPost(httpReq.Form)
	}
	resps := new(vector.Vector)
	for _, req := range reqs {
		resps.Push(this.respond(req))
	}
	conn.SetHeader("Content-Type", "application/json; charset=utf-8")
	json.NewEncoder(&keysToLowerWriter{conn}).Encode(resps)
}
Exemplo n.º 28
0
func createHandler(c *http.Conn, r *http.Request) {
	// read destAddr
	destAddr, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		http.Error(c, "Could not read destAddr",
			http.StatusInternalServerError)
		return
	}

	key := genKey()

	p, err := NewProxy(key, string(destAddr))
	if err != nil {
		http.Error(c, "Could not connect",
			http.StatusInternalServerError)
		return
	}
	createQueue <- p
	c.Write([]byte(key))
}
Exemplo n.º 29
0
func (set *TileServer) ServeHTTP(conn *http.Conn, req *http.Request) {
	req.ParseForm()
	var x, y, zoom int
	x, err := strconv.Atoi(req.Form["x"][0])
	if err == nil {
		y, err = strconv.Atoi(req.Form["y"][0])
	}
	if err == nil {
		zoom, err = strconv.Atoi(req.Form["z"][0])
	}

	if err != nil {
		fmt.Println("Err:", err.String())
		conn.WriteHeader(404)
		return
	}

	tile := set.GetTile(x, y, zoom)
	if tile == nil {
		fmt.Println("No tile at", x, y, zoom)
		conn.WriteHeader(404)
		return
	}
	conn.Write(tile)
}
Exemplo n.º 30
0
func add(c *http.Conn, req *http.Request) {
	if req.Method == "POST" && len(strings.TrimSpace(req.FormValue("code"))) > 0 {
		paste := savePaste(req.FormValue("code"), req.FormValue("private") != "")
		c.SetHeader("Location", "/view/"+paste)
		c.WriteHeader(http.StatusFound)
	} else {
		c.Write(strings.Bytes("No code submitted.\n"))
	}
}