nat/main.go

84 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
"github.com/dchest/uniuri"
2016-06-11 01:22:19 +00:00
"io"
"io/ioutil"
"net/http"
"os"
)
2016-06-11 01:22:19 +00:00
const (
2016-06-11 02:31:03 +00:00
DIRECTORY = "/tmp/"
ADDRESS = "http://localhost:8080"
LENGTH = 4
TEXT = "$ <command> | curl -F 'paste=<-'" + ADDRESS + "\n"
PORT = ":8080"
2016-06-11 01:22:19 +00:00
)
2016-06-10 14:29:22 +00:00
func check(e error) {
if e != nil {
panic(e)
}
}
func exists(location string) bool {
if _, err := os.Stat(location); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func generateName() string {
2016-06-11 02:31:03 +00:00
s := uniuri.NewLen(LENGTH)
file := exists(DIRECTORY + s)
2016-06-10 14:29:22 +00:00
if file == true {
generateName()
}
return s
}
2016-06-11 02:31:03 +00:00
func save(raw []byte) string {
paste := raw[92 : len(raw)-46]
s := generateName()
2016-06-11 02:31:03 +00:00
location := DIRECTORY + s
2016-06-11 01:22:19 +00:00
err := ioutil.WriteFile(location, paste, 0644)
check(err)
2016-06-11 01:22:19 +00:00
return s
}
2016-06-10 14:29:22 +00:00
func pasteHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
param := r.URL.RawQuery
if param != "" {
2016-06-11 02:31:03 +00:00
d := DIRECTORY + param
s, err := ioutil.ReadFile(d)
check(err)
io.WriteString(w, string(s))
} else {
2016-06-11 02:31:03 +00:00
io.WriteString(w, TEXT)
}
2016-06-10 14:29:22 +00:00
case "POST":
2016-06-11 02:22:22 +00:00
buf, err := ioutil.ReadAll(r.Body)
check(err)
2016-06-11 02:31:03 +00:00
io.WriteString(w, ADDRESS+"?"+save(buf)+"\n")
2016-06-10 14:29:22 +00:00
case "DELETE":
// Remove the record.
}
}
func main() {
http.HandleFunc("/", pasteHandler)
2016-06-11 02:31:03 +00:00
err := http.ListenAndServe(PORT, nil)
2016-06-11 02:22:22 +00:00
check(err)
}