You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.4 KiB
Go

10 years ago
package main
import (
"fmt"
10 years ago
"github.com/jordanorelli/moon/lib"
10 years ago
"io"
"net/http"
"net/http/httputil"
"os"
"strings"
10 years ago
"time"
10 years ago
"unicode"
)
10 years ago
var (
client = new(http.Client)
)
10 years ago
10 years ago
var config struct {
ProxyAddr string `
name: proxy_addr
default: ":8080"
help: proxy address. Browsers send their http traffic to this port.
`
AppAddr string `
name: app_addr
default: ":9000"
help: app address. Users visit this address to view the proxy's history db
`
DbPath string `
name: dbpath
default: history.db
help: path to a sqlite file used for storing the user's history
`
}
10 years ago
func httpHandler(w http.ResponseWriter, r *http.Request) {
id := newRequestId()
10 years ago
fmt.Printf("%s >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", id.String())
10 years ago
fmt.Println("from:", r.RemoteAddr)
10 years ago
if err := freezeRequest(r); err != nil {
fmt.Printf("error freezing request: %s\n", err)
return
}
10 years ago
b, err := httputil.DumpRequest(r, true)
if err != nil {
fmt.Printf("error dumping request: %s\n", err)
return
}
os.Stdout.Write(b)
10 years ago
requestURI := r.RequestURI
10 years ago
r.RequestURI = ""
r.URL.Scheme = strings.Map(unicode.ToLower, r.URL.Scheme)
10 years ago
start := time.Now()
10 years ago
res, err := client.Do(r)
if err != nil {
fmt.Printf("error forwarding request: %s\n", err)
return
}
defer res.Body.Close()
10 years ago
fmt.Printf("%s <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", id.String())
resb, err := httputil.DumpResponse(res, false)
if err != nil {
fmt.Printf("fuuuuuuuuuck")
}
os.Stdout.Write(resb)
10 years ago
for k, v := range res.Header {
w.Header()[k] = v
}
10 years ago
if _, ok := w.Header()["Proxy-Connection"]; ok {
delete(w.Header(), "Proxy-Connection")
}
10 years ago
w.WriteHeader(res.StatusCode)
if _, err := io.Copy(w, res.Body); err != nil {
fmt.Printf("error copying body: %s\n", err)
}
10 years ago
elapsed := time.Since(start)
10 years ago
r.RequestURI = requestURI
10 years ago
fmt.Printf("elapsed: %v (%v)\n", elapsed, elapsed.Nanoseconds()/1000000)
10 years ago
saveRequest(id, r)
saveResponse(id, res, elapsed)
10 years ago
}
10 years ago
func bail(status int, t string, args ...interface{}) {
if status == 0 {
fmt.Fprintf(os.Stdout, t+"\n", args...)
} else {
fmt.Fprintf(os.Stderr, t+"\n", args...)
}
os.Exit(status)
}
10 years ago
func proxyListener() {
m := http.NewServeMux()
m.HandleFunc("/", httpHandler)
10 years ago
http.ListenAndServe(config.ProxyAddr, m)
10 years ago
}
10 years ago
func main() {
10 years ago
moon.Parse(&config)
10 years ago
if err := openDB(); err != nil {
bail(1, "unable to open db: %s", err)
}
defer db.Close()
10 years ago
go appServer()
proxyListener()
10 years ago
}