Example #1
0
func serveFile(c *http.Conn, r *http.Request) {
	path := pathutil.Join(".", r.URL.Path)

	// pick off special cases and hand the rest to the standard file server
	switch ext := pathutil.Ext(path); {
	case r.URL.Path == "/":
		serveHTMLDoc(c, r, "doc/root.html")
		return

	case r.URL.Path == "/doc/root.html":
		// hide landing page from its real name
		http.NotFound(c, r)
		return

	case ext == ".html":
		if strings.HasSuffix(path, "/index.html") {
			// We'll show index.html for the directory.
			// Use the dir/ version as canonical instead of dir/index.html.
			http.Redirect(c, r.URL.Path[0:len(r.URL.Path)-len("index.html")], http.StatusMovedPermanently)
			return
		}
		serveHTMLDoc(c, r, path)
		return

	case ext == ".go":
		serveGoSource(c, r, path)
		return
	}

	dir, err := os.Lstat(path)
	if err != nil {
		http.NotFound(c, r)
		return
	}

	if dir != nil && dir.IsDirectory() {
		if redirect(c, r) {
			return
		}
		if index := path + "/index.html"; isTextFile(index) {
			serveHTMLDoc(c, r, index)
			return
		}
		serveDirectory(c, r, path)
		return
	}

	if isTextFile(path) {
		serveTextFile(c, r, path)
		return
	}

	fileServer.ServeHTTP(c, r)
}
Example #2
0
// Given a described blob, optionally follows a camliContent and
// returns the file's schema blobref and its fileinfo (if found).
func (pr *publishRequest) fileSchemaRefFromBlob(des *search.DescribedBlob) (fileref *blobref.BlobRef, fileinfo *search.FileInfo, ok bool) {
	if des == nil {
		http.NotFound(pr.rw, pr.req)
		return
	}
	if des.Permanode != nil {
		// TODO: get "forceMime" attr out of the permanode? or
		// fileName content-disposition?
		if cref := des.Permanode.Attr.Get("camliContent"); cref != "" {
			cbr := blobref.Parse(cref)
			if cbr == nil {
				http.Error(pr.rw, "bogus camliContent", 500)
				return
			}
			des = des.PeerBlob(cbr)
			if des == nil {
				http.Error(pr.rw, "camliContent not a peer in describe", 500)
				return
			}
		}
	}
	if des.CamliType == "file" {
		return des.BlobRef, des.File, true
	}
	http.Error(pr.rw, "failed to find fileSchemaRefFromBlob", 404)
	return
}
Example #3
0
func handle_http(responseWrite http.ResponseWriter, request *http.Request) {
	var proxyResponse *http.Response
	var proxyResponseError os.Error

	proxyHost := strings.Split(request.URL.Path[6:], "/")[0]

	fmt.Printf("%s %s %s\n", request.Method, request.RawURL, request.RemoteAddr)
	//TODO https
	url := "http://" + request.URL.Path[6:]
	proxyRequest, _ := http.NewRequest(request.Method, url, nil)
	proxy := &http.Client{}
	proxyResponse, proxyResponseError = proxy.Do(proxyRequest)
	if proxyResponseError != nil {
		http.NotFound(responseWrite, request)
		return
	}
	for header := range proxyResponse.Header {
		responseWrite.Header().Add(header, proxyResponse.Header.Get(header))
	}
	contentType := strings.Split(proxyResponse.Header.Get("Content-Type"), ";")[0]
	if proxyResponseError != nil {
		fmt.Fprintf(responseWrite, "pizda\n")
	} else if ReplacemendContentType[contentType] {
		body, _ := ioutil.ReadAll(proxyResponse.Body)
		defer proxyResponse.Body.Close()
		bodyString := replace_url(string(body), "/http/", proxyHost)

		responseWrite.Write([]byte(bodyString))

	} else {
		io.Copy(responseWrite, proxyResponse.Body)
	}
}
Example #4
0
func handle(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	// Fast path the root request.
	if path == "/" {
		render(chromeBytes, w)
		return
	}
	switch path[1] {
	case '.':
		switch path {
		case "/.rpc":
			rpc.Handle(path, w, r)
		case "/.test":
			render(testChromeBytes, w)
		default:
			rpc.HandleStream(path[2:], w, r)
		}
	case '_':
		switch path {
		case "/_ah/start":
			backend.Start(w, r)
		case "/_ah/stop":
			backend.Stop(w, r)
		default:
			http.NotFound(w, r)
		}
	default:
		render(chromeBytes, w)
	}
}
Example #5
0
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)
	}
}
Example #6
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)
}
Example #7
0
File: godoc.go Project: 8l/go-learn
func serveFile(c *http.Conn, r *http.Request) {
	path := r.Url.Path

	// pick off special cases and hand the rest to the standard file server
	switch ext := pathutil.Ext(path); {
	case path == "/":
		serveHtmlDoc(c, r, "doc/root.html")

	case r.Url.Path == "/doc/root.html":
		// hide landing page from its real name
		http.NotFound(c, r)

	case ext == ".html":
		serveHtmlDoc(c, r, path)

	case ext == ".go":
		serveGoSource(c, path, &Styler{highlight: r.FormValue("h")})

	default:
		// TODO:
		// - need to decide what to serve and what not to serve
		// - don't want to download files, want to see them
		fileServer.ServeHTTP(c, r)
	}
}
Example #8
0
func rootHandler(w http.ResponseWriter, r *http.Request) {
	p, err := loadPage(w, r)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	fmt.Fprintf(w, "%s", p.Body)
}
Example #9
0
File: nash.go Project: mutsuda/Nash
func getTitle(w http.ResponseWriter, r *http.Request) (title string, err os.Error) {
	title = r.URL.Path[lenPath:]
	if !titleValidator.MatchString(title) {
		http.NotFound(w, r)
		err = os.NewError("Invalid Page Title")
	}
	return
}
Example #10
0
func getKey(w http.ResponseWriter, r *http.Request, lenPath int) (key string, err os.Error) {
	var keyValidator = regexp.MustCompile("^[a-zA-Z0-9]+$")
	key = r.URL.Path[lenPath:]
	if !keyValidator.MatchString(key) {
		http.NotFound(w, r)
		err = os.NewError("Invalid Lookup Key")
	}
	return
}
Example #11
0
File: main.go Project: rsec/goto
func Redirect(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[1:]
	url := store.Get(key)
	if url == "" {
		http.NotFound(w, r)
		return
	}
	http.Redirect(w, r, url, http.StatusFound)
}
Example #12
0
func makePageHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		title := r.URL.Path[lenPath:]
		if !titleValidator.MatchString(title) {
			http.NotFound(w, r)
		}
		fn(w, r, title)
	}
}
Example #13
0
func serveFile(c *http.Conn, r *http.Request) {
	path := pathutil.Join(".", r.URL.Path)

	// pick off special cases and hand the rest to the standard file server
	switch ext := pathutil.Ext(path); {
	case r.URL.Path == "/":
		serveHTMLDoc(c, r, "doc/root.html")
		return

	case r.URL.Path == "/doc/root.html":
		// hide landing page from its real name
		http.NotFound(c, r)
		return

	case ext == ".html":
		serveHTMLDoc(c, r, path)
		return

	case ext == ".go":
		serveGoSource(c, r, path, &Styler{highlight: r.FormValue("h")})
		return
	}

	dir, err := os.Lstat(path)
	if err != nil {
		http.NotFound(c, r)
		return
	}

	if dir != nil && dir.IsDirectory() {
		serveDirectory(c, r, path)
		return
	}

	if isTextFile(path) {
		serveTextFile(c, r, path)
		return
	}

	fileServer.ServeHTTP(c, r)
}
Example #14
0
File: http.go Project: Crest/gresec
func GetNodeByName(store *NodeStore) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		setContentText(w)
		name := req.URL.Path[lenNamePath:]
		node, present := store.Get(name)
		if present {
			fmt.Fprintln(w, node)
		} else {
			http.NotFound(w, req)
		}
	}
}
Example #15
0
File: main.go Project: rsec/goto
func Redirect(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[1:]
	if key == "favicon.ico" || key == "" {
		http.NotFound(w, r)
		return
	}
	var url string
	if err := store.Get(&key, &url); err != nil {
		http.Error(w, err.String(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, url, http.StatusFound)
}
Example #16
0
// http.ServeFile won't let us set our own Content-Type
func serveFile(repo *Repo, w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		// forbidden?
		return
	}
	name := repo.file(r.URL.Path)
	f, err := os.Open(name)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	defer f.Close()
	io.Copy(w, f)
}
Example #17
0
func (handler *BaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer errorHandling(w, r)
	switch r.Method {
	case "POST":
		handler.Self.Post(JsonResponse{w}, (*JsonRequest)(r))
	case "GET":
		handler.Self.Get(JsonResponse{w}, r)
	case "PUT":
		handler.Self.Put(JsonResponse{w}, (*JsonRequest)(r))
	case "DELETE":
		handler.Self.Delete(JsonResponse{w}, r)
	default:
		http.NotFound(w, r)
	}
}
Example #18
0
File: main.go Project: kenu/You.RL
func Redirect(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[1:]

	if key == "favicon.ico" {
		http.NotFound(w, r)
	} else if key == "" {
		logo := &Title{Logo: "You.RL"}
		tpl, _ := template.ParseFile("index.html", nil)
		tpl.Execute(w, logo)
	} else if key == "index.js" {
		http.ServeFile(w, r, "index.js")
	} else {
		var url string
		store.Get(&key, &url)
		http.Redirect(w, r, url, http.StatusFound)
	}
}
Example #19
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)
	}
}
Example #20
0
func serveDirectory(c *http.Conn, r *http.Request, path string) {
	if redirect(c, r) {
		return
	}

	list, err := io.ReadDir(path)
	if err != nil {
		http.NotFound(c, r)
		return
	}

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

	servePage(c, "Directory "+path, "", buf.Bytes())
}
Example #21
0
func serveHTMLDoc(c *http.Conn, r *http.Request, path string) {
	// get HTML body contents
	src, err := io.ReadFile(path)
	if err != nil {
		log.Stderrf("%v", err)
		http.NotFound(c, r)
		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)
}
Example #22
0
func getTitle(w http.ResponseWriter, r *http.Request) (title string, err os.Error) {

	switch {

	case strings.Contains(r.URL.Path, view):
		title = r.URL.Path[lenViewPath:]

	case strings.Contains(r.URL.Path, edit):
		title = r.URL.Path[lenEditPath:]

	case strings.Contains(r.URL.Path, save):
		title = r.URL.Path[lenSavePath:]

	case strings.Contains(r.URL.Path, tag):
		title = "dontcare"

	}

	if !titleValidator.MatchString(title) {
		http.NotFound(w, r)
		err = os.NewError(errorInvalidPageTitle)
	}
	return
}
Example #23
0
func (handler *BaseHandler) Delete(w JsonResponse, r *http.Request) {
	http.NotFound(w, r)
}
Example #24
0
func (handler *BaseHandler) Put(w JsonResponse, r *JsonRequest) {
	http.NotFound(w, (*http.Request)(r))
}
Example #25
0
func HandleStream(path string, w http.ResponseWriter, r *http.Request) {

	call := strings.Split(path, "/")
	name := call[0]
	sr := streamServices.Lookup(name)

	if sr == nil {
		http.NotFound(w, r)
		return
	}

	var (
		ctx  *Context
		resp []byte
		sent bool
	)

	defer func() {
		if ctx != nil {
			freeContext(ctx)
		}
		if !sent {
			if e := recover(); e != nil {
				if redir, yes := e.(redirect); yes {
					http.Redirect(w, r, string(redir), 302)
					return
				}
				http.Error(w, fmt.Sprint(e), 500)
			} else {
				w.Write(resp)
			}
		}
	}()

	if r.Method != "GET" {
		http.Error(w, fmt.Sprintf("bad request: required GET, received %s", r.Method), 405)
		sent = true
		return
	}

	s := sr.(*service)
	diff := s.in + 1 - len(call)

	if diff < 0 {
		http.Error(w, fmt.Sprintf("bad request: too many arguments for %s", name), 400)
		sent = true
		return
	}

	for diff > 0 {
		call = append(call, "")
		diff -= 1
	}

	ctx = getContext()
	args := make([]reflect.Value, s.in+1)
	for i, param := range call {
		if i == 0 {
			continue
		}
		args[i] = reflect.ValueOf(param)
	}

	ctx.App = appengine.NewContext(r)
	ctx.Header = nil
	ctx.RespHeader = nil

	args[0] = reflect.ValueOf(ctx)
	rargs := s.meth.Call(args)

	if len(rargs) == 0 {
		resp = doneOK
	} else {
		var (
			ct string
			v  interface{}
		)
		if len(rargs) == 2 {
			ct = rargs[0].String()
			v = rargs[1].Interface()
		} else {
			ct = "text/plain; charset=utf-8"
			v = rargs[0].Interface()
		}
		if reader, ok := v.(io.ReadCloser); ok {
			resp, _ = ioutil.ReadAll(reader)
			reader.Close()
		} else if reader, ok := v.(io.Reader); ok {
			resp, _ = ioutil.ReadAll(reader)
		} else if stream, ok := v.([]byte); ok {
			resp = stream
		} else if stream, ok := v.(string); ok {
			resp = []byte(stream)
		} else {
			panic("unsupported response type: " + reflect.TypeOf(v).Kind().String())
		}
		w.Header().Set("Content-Type", ct)
	}

}
Example #26
-1
func Static(w http.ResponseWriter, r *http.Request) {
	filename := r.URL.Path[1:]
	if filename == "" {
		filename = "index.html"
	} else if filename[:6] != "flotr/" {
		http.NotFound(w, r)
		return
	}
	http.ServeFile(w, r, "static/"+filename)
}