Skip to content

Commit

Permalink
Support trans-localfile option use a nother way.
Browse files Browse the repository at this point in the history
  • Loading branch information
hanxi committed May 15, 2019
1 parent e584c4d commit fe39bb0
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 9 deletions.
50 changes: 49 additions & 1 deletion client/client.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package client

import (
"bytes"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strconv"
"strings"

Expand Down Expand Up @@ -62,7 +66,51 @@ func (c *client) Paste() (string, error) {
return lemon.ConvertLineEnding(string(body), c.lineEnding), nil
}

func (c *client) Open(uri string, transLoopback bool) error {
func fileExists(fname string) bool {
_, err := os.Stat(fname)
return err == nil
}

func (c *client) postFile(name string, url string) (*http.Response, error) {
bodyBuf := bytes.NewBufferString("")
bodyWriter := multipart.NewWriter(bodyBuf)

fileWriter, err := bodyWriter.CreateFormFile("uploadFile", name)
if err != nil {
c.logger.Error("Writing to buffer", "name", name)
return nil, err
}

file, err := os.Open(name)
if err != nil {
c.logger.Error("cant Opening file", "name", name)
return nil, err
}

_, err = io.Copy(fileWriter, file)
if err != nil {
return nil, err
}

contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
return http.Post(url, contentType, bodyBuf)
}

func (c *client) uploadFile(name string) error {
url := fmt.Sprintf("%s/upload?open=true", c.addr)
_, err := c.postFile(name, url)
if err != nil {
return err
}
return nil
}

func (c *client) Open(uri string, transLocalfile bool, transLoopback bool) error {
if transLocalfile && fileExists(uri) {
return c.uploadFile(uri)
}

url := fmt.Sprintf("%s/open?uri=%s&transLoopback=%s&base64=true", c.addr, base64.URLEncoding.EncodeToString([]byte(uri)), strconv.FormatBool(transLoopback))
c.logger.Info("Opening: " + uri)

Expand Down
13 changes: 7 additions & 6 deletions lemon/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@ type CLI struct {
DataSource string

// options
Port int
Allow string
Host string
TransLoopback bool
LineEnding string
LogLevel int
Port int
Allow string
Host string
TransLoopback bool
TransLocalfile bool
LineEnding string
LogLevel int

Help bool

Expand Down
1 change: 1 addition & 0 deletions lemon/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ func (c *CLI) flags() *flag.FlagSet {
flags.StringVar(&c.Host, "host", "localhost", "Destination host name.")
flags.BoolVar(&c.Help, "help", false, "Show this message")
flags.BoolVar(&c.TransLoopback, "trans-loopback", true, "Translate loopback address")
flags.BoolVar(&c.TransLocalfile, "trans-localfile", true, "Translate local file")
flags.StringVar(&c.LineEnding, "line-ending", "", "Convert Line Endings (CR/CRLF)")
flags.BoolVar(&c.NoFallbackMessages, "no-fallback-messages", false, "Do not show fallback messages")
flags.IntVar(&c.LogLevel, "log-level", 1, "Log level")
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func Do(c *lemon.CLI, args []string) int {
switch c.Type {
case lemon.OPEN:
logger.Debug("Opening URL")
err = lc.Open(c.DataSource, c.TransLoopback)
err = lc.Open(c.DataSource, c.TransLocalfile, c.TransLoopback)
case lemon.COPY:
logger.Debug("Copying text")
err = lc.Copy(c.DataSource)
Expand Down
44 changes: 43 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/url"
"os"

"github.com/atotto/clipboard"
log "github.com/inconshreveable/log15"
Expand All @@ -19,6 +20,8 @@ import (
var logger log.Logger
var lineEnding string
var ra *iprange.Range
var port int
var path = "./files"

func handleCopy(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Expand All @@ -33,7 +36,9 @@ func handleCopy(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), 500)
return
}
clipboard.WriteAll(lemon.ConvertLineEnding(string(b), lineEnding))
text := lemon.ConvertLineEnding(string(b), lineEnding)
logger.Debug("Copy:", "text", text)
clipboard.WriteAll(text)
}

func handlePaste(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -99,6 +104,39 @@ func handleOpen(w http.ResponseWriter, r *http.Request) {
open.Run(uri)
}

func handleUpload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Upload only support post", 404)
return
}

r.ParseMultipartForm(10 << 20)
file, handler, err := r.FormFile("uploadFile")
if err != nil {
http.Error(w, "Error Retrieving the File", 500)
logger.Error("Error Retrieving the File", "err", err)
return
}
defer file.Close()

fileBytes, err := ioutil.ReadAll(file)
if err != nil {
http.Error(w, "Error Read the File", 500)
logger.Error("Error Read the File", "err", err)
return
}

ioutil.WriteFile(path+"/"+handler.Filename, fileBytes, os.ModePerm)

q := r.URL.Query()
isOpen := q.Get("open")
if isOpen == "true" {
uri := fmt.Sprintf("http://127.0.0.1:%d/files/%s", port, handler.Filename)
logger.Info("Open: ", "uri", uri)
open.Run(uri)
}
}

func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodPost {
Expand All @@ -123,6 +161,7 @@ func middleware(next http.Handler) http.Handler {
func Serve(c *lemon.CLI, _logger log.Logger) error {
logger = _logger
lineEnding = c.LineEnding
port = c.Port

var err error
ra, err = iprange.New(c.Allow)
Expand All @@ -131,9 +170,12 @@ func Serve(c *lemon.CLI, _logger log.Logger) error {
return err
}

os.MkdirAll(path, os.ModePerm)
http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(path))))
http.Handle("/copy", middleware(http.HandlerFunc(handleCopy)))
http.Handle("/paste", middleware(http.HandlerFunc(handlePaste)))
http.Handle("/open", middleware(http.HandlerFunc(handleOpen)))
http.Handle("/upload", middleware(http.HandlerFunc(handleUpload)))
err = http.ListenAndServe(fmt.Sprintf(":%d", c.Port), nil)
if err != nil {
return err
Expand Down

0 comments on commit fe39bb0

Please sign in to comment.