Esempio n. 1
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?
	}
}
Esempio n. 2
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)
}
Esempio n. 3
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))
}
Esempio n. 4
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)
}
Esempio 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)
}
Esempio n. 6
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"))
	}
}
Esempio n. 7
0
func (proxy *Proxy) ServeHTTP(conn *http.Conn, req *http.Request) {

	// Open a connection to the Hub.
	hubconn, err := net.Dial("tcp", "", remoteAddr)
	if err != nil {
		if debugMode {
			fmt.Printf("Couldn't connect to remote %s: %v\n", remoteHost, err)
		}
		return
	}

	hub := tls.Client(hubconn, tlsconf.Config)
	defer hub.Close()

	// Modify the request Host: header.
	req.Host = remoteHost

	// Send the request to the Hub.
	err = req.Write(hub)
	if err != nil {
		if debugMode {
			fmt.Printf("Error writing to the hub: %v\n", err)
		}
		return
	}

	// Parse the response from the Hub.
	resp, err := http.ReadResponse(bufio.NewReader(hub), req.Method)
	if err != nil {
		if debugMode {
			fmt.Printf("Error parsing response from the hub: %v\n", err)
		}
		return
	}

	// Set the received headers back to the initial connection.
	for k, v := range resp.Header {
		conn.SetHeader(k, v)
	}

	// Read the full response body.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		if debugMode {
			fmt.Printf("Error reading response from the hub: %v\n", err)
		}
		resp.Body.Close()
		return
	}

	// Write the response body back to the initial connection.
	resp.Body.Close()
	conn.WriteHeader(resp.StatusCode)
	conn.Write(body)

}
Esempio n. 8
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"))
	}
}
Esempio n. 9
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))
}
Esempio n. 10
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"))
	}
}
Esempio n. 11
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)
	}
}
Esempio n. 12
0
File: main.go Progetto: 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;
}
Esempio n. 13
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)
	}
}
Esempio n. 14
0
File: web.go Progetto: 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)
	}
}
Esempio n. 15
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))
}
Esempio n. 16
0
func ServeTestHTTP(conn *http.Conn, req *http.Request) {
	req.Close = true
	if api_key, ok := req.Header["Authorization"]; !ok || api_key != API_KEY {
		text := []byte(ERROR_CODES[http.StatusUnauthorized])
		conn.SetHeader("Content-Type", "text/html;charset=ISO-8859-1")
		conn.SetHeader("Cache-Control", "must-revalidate,no-cache,no-store")
		conn.SetHeader("Content-Length", strconv.Itoa(len(text)))
		conn.WriteHeader(http.StatusUnauthorized)
		conn.Write(text)
		conn.Flush()
		return
	}
	if text, ok := URL_MAPPINGS[req.URL.Path]; ok {
		conn.SetHeader("Content-Type", "application/xml;charset=UTF-8")
		conn.SetHeader("Transfer-Encoding", "chunked")
		// for some reason, api.rapleaf.com does not send Content-Length
		// when sending stored data
		conn.WriteHeader(http.StatusOK)
		conn.Write([]byte(text))
		conn.Flush()
		return
	}
	text := []byte(ERROR_CODES[http.StatusNotFound])
	conn.SetHeader("Content-Type", "text/html;charset=ISO-8859-1")
	conn.SetHeader("Cache-Control", "must-revalidate,no-cache,no-store")
	conn.SetHeader("Content-Length", strconv.Itoa(len(text)))
	conn.WriteHeader(http.StatusNotFound)
	conn.Write(text)
	conn.Flush()
	return
}
Esempio n. 17
0
func serveText(c *http.Conn, text []byte) {
	c.SetHeader("content-type", "text/plain; charset=utf-8")
	c.Write(text)
}
Esempio n. 18
0
func (frontend *Frontend) ServeHTTP(conn *http.Conn, req *http.Request) {

	if frontend.enforceHost && req.Host != frontend.officialHost {
		conn.SetHeader("Location", frontend.officialRedirectURL)
		conn.WriteHeader(http.StatusMovedPermanently)
		conn.Write(frontend.officialRedirectHTML)
		logRequest(http.StatusMovedPermanently, req.Host, conn)
		return
	}

	originalHost := req.Host

	// Open a connection to the App Engine server.
	gaeConn, err := net.Dial("tcp", "", frontend.gaeAddr)
	if err != nil {
		if debugMode {
			fmt.Printf("Couldn't connect to remote %s: %v\n", frontend.gaeHost, err)
		}
		serveError502(conn, originalHost)
		return
	}

	var gae net.Conn

	if frontend.gaeTLS {
		gae = tls.Client(gaeConn, tlsconf.Config)
		defer gae.Close()
	} else {
		gae = gaeConn
	}

	// Modify the request Host: header.
	req.Host = frontend.gaeHost

	// Send the request to the App Engine server.
	err = req.Write(gae)
	if err != nil {
		if debugMode {
			fmt.Printf("Error writing to App Engine: %v\n", err)
		}
		serveError502(conn, originalHost)
		return
	}

	// Parse the response from App Engine.
	resp, err := http.ReadResponse(bufio.NewReader(gae), req.Method)
	if err != nil {
		if debugMode {
			fmt.Printf("Error parsing response from App Engine: %v\n", err)
		}
		serveError502(conn, originalHost)
		return
	}

	// Read the full response body.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		if debugMode {
			fmt.Printf("Error reading response from App Engine: %v\n", err)
		}
		serveError502(conn, originalHost)
		resp.Body.Close()
		return
	}

	// Set the received headers back to the initial connection.
	for k, v := range resp.Header {
		conn.SetHeader(k, v)
	}

	// Write the response body back to the initial connection.
	resp.Body.Close()
	conn.WriteHeader(resp.StatusCode)
	conn.Write(body)

	logRequest(resp.StatusCode, originalHost, conn)

}
Esempio n. 19
0
func Logger(c *http.Conn, req *http.Request) {
	log.Stdout(req.URL.Raw)
	c.WriteHeader(404)
	c.Write([]byte("oops"))
}
Esempio n. 20
0
func List(c *http.Conn, req *http.Request) {
	players := room.List()
	c.Write([]byte(strings.Join(players, ",")))
}
Esempio n. 21
0
func handler(conn *http.Conn, req *http.Request) {
	conn.SetHeader("Content-Type", "text/plain")
	conn.Write(Resp)
}
Esempio n. 22
0
func allPaged(c *http.Conn, req *http.Request, page int) {
	files, ok := io.ReadDir(PATH)
	sort.Sort(pasteList(files))

	if ok != nil {
		c.Write(strings.Bytes("Error reading pastes directory.\n"))
		return
	}

	offset := PER_PAGE * (page - 1)

	limit := len(files) - offset
	if limit > PER_PAGE {
		limit = PER_PAGE
	}

	if limit < 0 {
		c.Write(strings.Bytes("Page too far.\n"))
		return
	}

	pastes := make([]string, limit)
	for i, j := 0, offset; j < offset+limit; j++ {
		if strings.HasPrefix(files[j].Name, "private:") {
			limit++
			continue
		}

		pastes[i] = files[j].Name
		i++
	}

	prev := ""
	if page > 1 {
		prev = "/all/page/" + strconv.Itoa(page-1)
	}

	next := ""
	if len(files)/PER_PAGE > page {
		next = "/all/page/" + strconv.Itoa(page+1)
	}

	codeList := make([]string, len(pastes))
	results := make(chan int)
	for i, paste := range pastes {
		go func(i int, paste string) {
			code, err := prettyPaste(paste, 10)
			if err != nil {
				code[0] = err.String()
			}

			codeList[i] =
				fmt.Sprintf(
					H2(
						"Paste ",
						A("#%s").Attrs(As{
							"href": "/view/%s",
						})).Out(),
					paste, paste) + code[0]

			results <- i
		}(i, paste)
	}

	for i := 0; i < len(pastes); i++ {
		<-results
	}

	theme := curTheme(req)
	allPage.Execute(allEnv{prev, next, codeList, theme, themeSelect(theme)}, c)
}