2 Commits

Author SHA1 Message Date
1caec97d81 Add basic client
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-01-16 21:51:04 +01:00
786ae6ad94 Handle multipart form files
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-01-16 21:29:42 +01:00
5 changed files with 171 additions and 4 deletions

16
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug server",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/server/server.go",
"cwd": "${workspaceFolder}"
}
]
}

View File

@@ -1,7 +1,106 @@
package main
import "fmt"
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"time"
"github.com/google/uuid"
"github.com/urfave/cli/v2"
)
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
fmt.Println("Starting gpaste client")
cli.VersionFlag = &cli.BoolFlag{Name: "version"}
app := cli.App{
Name: "gpaste",
Version: fmt.Sprintf("gpaste %s-%s (%s)", version, commit, date),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Usage: "Path to config-file.",
},
},
Commands: []*cli.Command{
{
Name: "upload",
Usage: "Upload file(s)",
ArgsUsage: "FILE [FILE]...",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "url",
Usage: "Base url of gpaste server",
},
},
Action: ActionUpload,
},
},
}
app.Run(os.Args)
}
func ActionUpload(c *cli.Context) error {
url := fmt.Sprintf("%s/api/file", c.String("url"))
client := &http.Client{}
// TODO: Change timeout
ctx, cancel := context.WithTimeout(c.Context, 10*time.Minute)
defer cancel()
buf := &bytes.Buffer{}
mw := multipart.NewWriter(buf)
for _, arg := range c.Args().Slice() {
f, err := os.Open(arg)
if err != nil {
return err
}
defer f.Close()
fw, err := mw.CreateFormFile(uuid.Must(uuid.NewRandom()).String(), arg)
if err != nil {
return err
}
if _, err := io.Copy(fw, f); err != nil {
return err
}
}
mw.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, buf)
req.Header.Add("Content-Type", mw.FormDataContentType())
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var expectedResp []struct {
Message string `json:"message"`
ID string `json:"id"`
URL string `json:"url"`
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&expectedResp); err != nil {
return fmt.Errorf("error decoding response: %w", err)
}
for _, r := range expectedResp {
fmt.Printf("Uploaded file %s\n", r.ID)
}
return nil
}

View File

@@ -69,6 +69,7 @@ func ActionServe(c *cli.Context) error {
go func() {
srv := gpaste.NewHTTPServer(cfg)
srv.Addr = cfg.ListenAddr
srv.Logger = serverLogger
// Wait for cancel
go func() {

View File

@@ -6,8 +6,9 @@ import (
)
type File struct {
ID string
Body io.ReadCloser
ID string
OriginalFilename string
Body io.ReadCloser
MaxViews uint
ExpiresOn time.Time

50
http.go
View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"io"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
@@ -43,6 +44,12 @@ func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request)
Body: r.Body,
}
// Check if multipart form
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "multipart/form-data") {
s.processMultiPartFormUpload(w, r)
return
}
err := s.store.Store(f)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
@@ -85,3 +92,46 @@ func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) {
s.Logger.Warnw("Error writing file to client.", "error", err, "remote_addr", r.RemoteAddr)
}
}
func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.Request) {
s.Logger.Debugw("Processing multipart form.")
type resp struct {
Message string `json:"message"`
ID string `json:"id"`
URL string `json:"url"`
}
var responses []resp
if err := r.ParseMultipartForm(1024 * 1024 * 10); err != nil {
s.Logger.Warnw("Error parsing multipart form.", "err", err)
}
for k := range r.MultipartForm.File {
ff, fh, err := r.FormFile(k)
if err != nil {
s.Logger.Warnw("Error reading file from multipart form.", "error", err)
return
}
f := &File{
ID: uuid.Must(uuid.NewRandom()).String(),
OriginalFilename: fh.Filename,
Body: ff,
}
if err := s.store.Store(f); err != nil {
w.WriteHeader(http.StatusInternalServerError)
s.Logger.Warnw("Error storing file.", "erorr", err, "id", f.ID, "remote_addr", r.RemoteAddr)
return
}
s.Logger.Infow("Stored file.", "id", f.ID, "filename", f.OriginalFilename, "remote_addr", r.RemoteAddr)
responses = append(responses, resp{Message: "OK", ID: f.ID, URL: "TODO"})
}
w.WriteHeader(http.StatusAccepted)
encoder := json.NewEncoder(w)
if err := encoder.Encode(&responses); err != nil {
s.Logger.Warnw("Error encoding response to client.", "error", err, "remote_addr", r.RemoteAddr)
}
}