// 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 } } }
// 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 } }
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) }
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")) } }
// 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); }
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) }
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) } }
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()) } }) }
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") }
// 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); }
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) } }
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; }
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() }
func serveHTTP(c *http.Conn, req *http.Request) { if req.Method != "CONNECT" { c.SetHeader("Content-Type", "text/plain; charset=utf-8") c.WriteHeader(http.StatusMethodNotAllowed) io.WriteString(c, "405 must CONNECT to "+rpcPath+"\n") return } conn, _, err := c.Hijack() if err != nil { log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String()) return } io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n") server.input(conn) }
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.") } }
// 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"); } }
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; }
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) }
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) }
// url: /blog/entry/(\d+) // 1: ID of blog post to show. func Entry(c *http.Conn, req *http.Request) { idString := req.URL.String(); idString = idString[len("/blog/entry/"):len(idString)]; if entryID, parseErr := strconv.Atoi(idString); parseErr == nil { if foundEntry := blog.FindEntry(entryID); foundEntry != nil { var entry singlePageEntry; entry.Entry = foundEntry; entry.Comments = foundEntry.Comments.Data(); entry.CommentCount = len(entry.Comments); if tmpl, err := loadTemplate("entry.html"); err == nil { tmpl.Execute(entry, c); } else { c.SetHeader("Content-Type", "text/plain; charset=utf-8"); c.WriteHeader(http.StatusInternalServerError); io.WriteString(c, "500 internal server error\n"); } } else { c.SetHeader("Content-Type", "text/plain; charset=utf-8"); c.WriteHeader(http.StatusNotFound); io.WriteString(c, "404 not found\n"); } } else { c.SetHeader("Content-Type", "text/plain; charset=utf-8"); c.WriteHeader(http.StatusInternalServerError); io.WriteString(c, "500 internal server error\n"); } }
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) }
func PushServer(c *http.Conn, req *http.Request) { c.SetHeader("content-type", "text/plain; charset=utf-8") c.SetHeader("Server", "jonaz ajax server") hostname := strings.Split(c.Req.Host, ":") sess := req.FormValue("sess") //example http long fetch request //http://localhost:12345/?fetch&sess=112551 if sess != "" { _, test := sessions[sess+hostname[0]] if test { io.WriteString(c, "error, sessions already running fetch") sessions[sess+hostname[0]] = nil, false return } //sessions[sess].data = make(chan string); sessions[sess+hostname[0]] = make(chan string) killtimer := make(chan bool) go timer(sess+hostname[0], killtimer) value := <-sessions[sess+hostname[0]] killtimer <- true io.WriteString(c, "query: "+c.Req.URL.RawQuery+"\nPush: \n") fmt.Fprintf(c, "val: %s", value) os.Stdout.WriteString("Hostname: " + c.Req.Host + " (sess:" + value + ") ---") os.Stdout.WriteString("value.hostname: " + hostname[0] + "\n") sessions[sess+hostname[0]] = nil, false return } //safety check. dont want outsiders to push! if hostname[0] != "localhost" { io.WriteString(c, "only localhost allowed to push! Nothing to do.....") return } //example request to push to sessions in "to" variable //http://localhost:12345/?cmd=1&to=1,2,3,4,5,6,7,9,10,11,12,13,14&data=12ljalgijasljga if len(sessions) > 0 && req.FormValue("cmd") == "1" { fmt.Fprintf(c, "Time: %d\n", time.Seconds()) sendto := strings.Split(req.FormValue("to"), ",", 0) data := req.FormValue("data") host := req.FormValue("domain") for _, sendtoval := range sendto { _, test := sessions[sendtoval+host] if test { sessions[sendtoval+host] <- data io.WriteString(c, "sending to channel... var: "+data+"\n to session: "+sendtoval+"\nqueue: ") fmt.Fprintf(c, "Time: %d\n", time.Seconds()) } } return } io.WriteString(c, "Nothing to do.....") return }
func (this *api) ServeHTTP(conn *http.Conn, req *http.Request) { conn.SetHeader("Content-Type", "text/javascript; charset=utf-8") json.NewEncoder(&keysToLowerWriter{conn}).Encode(this.provider) }
// hello world, the web server func HelloServer(c *http.Conn, req *http.Request) { c.SetHeader("Content-Type", "image/svg+xml; charset=utf-8") page := strm.Int(req.URL.RawQuery, 1) - 1 io.WriteString(c, string(svg.Page(pd, page))) }
// Heap responds with the pprof-formatted heap profile. // The package initialization registers it as /debug/pprof/heap. func Heap(c *http.Conn, r *http.Request) { c.SetHeader("content-type", "text/plain; charset=utf-8") pprof.WriteHeapProfile(c) }
func echo(c *http.Conn, r *http.Request) { c.SetHeader("Content-Type", r.Header["Content-Type"]) io.Copy(c, r.Body) }
func handler(conn *http.Conn, req *http.Request) { conn.SetHeader("Content-Type", "text/plain") conn.Write(Resp) }
// Cmdline responds with the running program's // command line, with arguments separated by NUL bytes. // The package initialization registers it as /debug/pprof/cmdline. func Cmdline(c *http.Conn, r *http.Request) { c.SetHeader("content-type", "text/plain; charset=utf-8") fmt.Fprintf(c, strings.Join(os.Args, "\x00")) }
func serveText(c *http.Conn, text []byte) { c.SetHeader("content-type", "text/plain; charset=utf-8") c.Write(text) }
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 }