package main import ( "database/sql" "fmt" "html" "io" "io/ioutil" "log" "net/http" "github.com/gorilla/mux" "github.com/dchest/uniuri" "github.com/ewhal/pygments" _ "github.com/mattn/go-sqlite3" ) const ( ADDRESS = "http://localhost:9900" LENGTH = 6 TEXT = "$ | curl -F 'p=<-' " + ADDRESS + "\n" PORT = ":9900" ) func check(err error) { if err != nil { fmt.Println(err) } } func generateName() string { s := uniuri.NewLen(LENGTH) db, err := sql.Open("sqlite3", "./database.db") check(err) query, err := db.Query("select id from pastebin") for query.Next() { var id string err := query.Scan(&id) if err != nil { } if id == s { generateName() } } db.Close() return s } func save(raw []byte) string { paste := raw[86 : len(raw)-46] s := generateName() db, err := sql.Open("sqlite3", "./database.db") check(err) stmt, err := db.Prepare("INSERT INTO pastebin(id, hash, data, delkey) values(?,?,?,?)") _, err = stmt.Exec(s, html.EscapeString(string(paste))) check(err) db.Close() return s } func saveHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "POST": buf, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), 500) } name := save(buf) io.WriteString(w, ADDRESS+"/p/"+name+"\n") } } func rootHandler(w http.ResponseWriter, r *http.Request) { io.WriteString(w, TEXT) } func langHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) paste := vars["pasteId"] lang := vars["lang"] s := getPaste(paste) highlight := pygments.Highlight(html.UnescapeString(s), lang, "html", "full, style=autumn,linenos=True, lineanchors=True,anchorlinenos=True,", "utf-8") io.WriteString(w, highlight) } func getPaste(paste string) string { param1 := html.EscapeString(paste) db, err := sql.Open("sqlite3", "./database.db") var s string err = db.QueryRow("select data from pastebin where id=?", param1).Scan(&s) db.Close() check(err) if err == sql.ErrNoRows { return "Error invalid paste" } else { return html.UnescapeString(s) } } func pasteHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) paste := vars["pasteId"] s := getPaste(paste) io.WriteString(w, s) } func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", rootHandler) router.HandleFunc("/p/{pasteId}", pasteHandler) router.HandleFunc("/p/{pasteId}/{lang}", langHandler) router.HandleFunc("/save", saveHandler) router.HandleFunc("/save", saveHandler) err := http.ListenAndServe(PORT, router) if err != nil { log.Fatal(err) } }