pb/main.go

68 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-08-29 22:05:49 +00:00
package main
import (
"fmt"
"io"
"log"
"net/http"
2024-08-29 22:36:57 +00:00
"net/url"
2024-08-29 22:05:49 +00:00
"os"
2024-08-29 22:36:57 +00:00
"path"
2024-08-29 22:05:49 +00:00
"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)
}
2024-08-29 22:36:57 +00:00
os.WriteFile(path.Join("db", uuid.String()), body, 0644)
url, err := url.JoinPath(hostURL, uuid.String())
if err != nil {
log.Fatalln(err)
}
fmt.Fprintf(w, url)
2024-08-29 22:05:49 +00:00
log.Printf("paste created: uuid=%s", uuid.String())
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})
2024-08-29 22:36:57 +00:00
http.Handle("/", http.FileServer(http.Dir(databasePath)))
2024-08-29 22:05:49 +00:00
2024-08-29 22:36:57 +00:00
log.Printf("Starting server on %s", listenAddr)
2024-08-29 22:05:49 +00:00
log.Fatal(http.ListenAndServe(listenAddr, nil))
}