~porcellis/t

9ccc8779f3633e66a7352a68ecfd2b77fdca785e — Pedro Lucas Porcellis 2 years ago 181977b
Add command to share notes at a given provider

Currently, we're shipping a `rascunho` instance as a default pastebin
provider, as `rascunho` is also a markdown previewer as a bonus.

You can configure to a private instance if you want, tweaking your
personal `t.conf` file on the share section.

See more about rascunho at:

https://sr.ht/~porcellis/rascunho
2 files changed, 65 insertions(+), 0 deletions(-)

A commands/share.go
M main.go
A commands/share.go => commands/share.go +45 -0
@@ 0,0 1,45 @@
package commands

import (
	"bytes"
	"encoding/json"
	"fmt"
	"git.sr.ht/~porcellis/t/config"
	"git.sr.ht/~porcellis/t/models"
	"io/ioutil"
	"log"
	"net/http"
)

func Share(config config.TConfig, note models.Note) error {
	url := fmt.Sprintf("%s://%s", config.Share.Protocol, config.Share.Base)
	api := fmt.Sprintf("%s%s", url, config.Share.Path)

	contents, err := ioutil.ReadFile(note.Path)

	if err != nil {
		return err
		log.Fatalln(err)
	}

	requestBody, err := json.Marshal(map[string]string{
		"text": string(contents),
	})

	// TODO: Make this configurable
	response, err := http.Post(api, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		return err
		log.Fatalln(err)
	}

	defer response.Body.Close()

	var result map[string]interface{}

	json.NewDecoder(response.Body).Decode(&result)

	log.Println(fmt.Sprintf("%s/%s", url, result["sha"]))

	return nil
}

M main.go => main.go +20 -0
@@ 142,6 142,26 @@ func main() {
			panic("There was some error when trying to display the note")
		}

	case "share", "sh":
		var note models.Note
		notes, _ := commands.BuildList(*configuration)

		if len(os.Args) == 2 {
			note = notes[0]
		} else {
			index, err := strconv.Atoi(os.Args[2])

			if err == nil {
				note = notes[index]
			}
		}

		err = commands.Share(*configuration, note)

		if err != nil {
			panic(fmt.Sprintf("There was some error when trying to share the note, %s", err))
		}

	case "version", "v":
		println("t ", Version)