pb/main.go
2024-08-30 06:05:49 +08:00

60 lines
1.2 KiB
Go

package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/google/uuid"
)
const (
databasePath = "db"
hostURL = "http://127.0.0.1:8080/"
listenAddr = ":8080"
repoURL = "https://git.ny4.dev/nyancat/pb"
)
func main() {
if _, err := os.Stat(databasePath); os.IsNotExist(err) {
err := os.Mkdir(databasePath, 0755)
if err != nil {
log.Fatalln(err)
}
}
http.HandleFunc("/{$}", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
fmt.Fprintf(w, `pb
usage: curl --data-binary @<file> %s
or: cmd | curl --data-binary @- %s
(c) 2024 Guanran Wang, source code licensed under MIT.
%s
`, hostURL, hostURL, repoURL)
case http.MethodPut, http.MethodPost:
uuid, err := uuid.NewRandom()
if err != nil {
log.Fatalln(err)
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Fatalln(err)
}
os.WriteFile("db/"+uuid.String(), body, 0644)
fmt.Fprintf(w, hostURL+uuid.String())
log.Printf("paste created: uuid=%s", uuid.String())
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})
http.Handle("/", http.FileServer(http.Dir("db")))
log.Fatal(http.ListenAndServe(listenAddr, nil))
}