Skip to content

Commit

Permalink
Merge pull request #8 from abhi-g80/feature/use-echo
Browse files Browse the repository at this point in the history
Feature/use echo
  • Loading branch information
abhi-g80 authored Aug 24, 2022
2 parents 340cfc2 + 6646692 commit 0421109
Show file tree
Hide file tree
Showing 16 changed files with 208 additions and 231 deletions.
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

Chipku - a no frill pastebin 🗑️
==============================
Paste bin in Golang.
Pastebin in Golang.

This is an in-memory paste bin which tries to be extremely minimal and doesn't get in the way. Simply a tool to quickly share snippets. No backend databases, no code formatting or code commenting, no self-destructing messages.

Expand All @@ -14,7 +14,7 @@ If you restart the application, you **will lose** your snippets.
Installation
------------

You may download the standalone binary and run it as,
You may download the standalone binary from the [releases](https://github.com/abhi-g80/chipku/releases) section and run it as,

./chipku serve

Expand Down Expand Up @@ -53,12 +53,21 @@ Building the docker image and running it using docker-compose (serves over port

make up

Checking the logs

```bash
docker compose logs # or docker-compose logs
```

![dockerlogs](docs/dockerlogs.png "dockerlogs")

Structured logs for easy parsing in tools like Datadog.

For linting and local builds

make lint
make build


Credits
-------

Expand Down
16 changes: 8 additions & 8 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
package cmd

import (
"fmt"
"os"

"github.com/abhi-g80/chipku/server"
"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
// RootCmd the root command for chipku
var RootCmd = &cobra.Command{
Use: "chipku",
Short: "Chipku is a no frill pastebin",
Long: `A fast and reliable pastebin server.
May be used for sharing snippets with your loved ones and colleagues.
Partial documentation is available at http://github.com/abhi-go/chipku`,
Partial documentation is available at http://github.com/abhi-g80/chipku`,
Run: func(cmd *cobra.Command, args []string) {
// print cmd help if no serve subcommand isn't invoked
err := cmd.Help()
if err != nil {
server.ErrorLog.Print(err.Error())
os.Exit(1)
}
},
}

// Execute try to run the root command
func Execute() {
if err := rootCmd.Execute(); err != nil {
server.ErrorLog.Print(err.Error())
os.Exit(1)
func Execute() error {
if err := RootCmd.Execute(); err != nil {
return fmt.Errorf("root cmd: %v", err)
}
return nil
}
15 changes: 15 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package cmd_test

import (
"testing"

"github.com/abhi-g80/chipku/cmd"
)

func TestRootCmd(t *testing.T) {
err := cmd.Execute()

if err != nil {
t.Errorf("got error: %v", err)
}
}
10 changes: 6 additions & 4 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ package cmd
import (
"strconv"

"github.com/spf13/cobra"

"github.com/abhi-g80/chipku/server"
"github.com/spf13/cobra"
)

var port int
var debug bool

func init() {
rootCmd.AddCommand(serve)
RootCmd.AddCommand(serve)
serve.Flags().IntVarP(&port, "port", "p", 8080, "port to serve on")
serve.Flags().BoolVarP(&debug, "debug", "d", false, "print debug messages")
}

var serve = &cobra.Command{
Expand All @@ -21,6 +22,7 @@ var serve = &cobra.Command{
Long: `Start the Chipku server`,
Run: func(cmd *cobra.Command, args []string) {
p := strconv.Itoa(port)
server.Serve(p)
d := debug
server.Serve(p, d)
},
}
2 changes: 1 addition & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

func init() {
rootCmd.AddCommand(version)
RootCmd.AddCommand(version)
}

var version = &cobra.Command{
Expand Down
17 changes: 17 additions & 0 deletions cmd/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package cmd_test

import (
"testing"

"github.com/abhi-g80/chipku/cmd"
)

func TestVersionCmd(t *testing.T) {
var args []string = []string{"version"}
cmd.RootCmd.SetArgs(args)
err := cmd.RootCmd.Execute()

if err != nil {
t.Errorf("got error: %v", err)
}
}
Binary file added docs/dockerlogs.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ module github.com/abhi-g80/chipku
go 1.16

require (
github.com/gorilla/mux v1.8.0
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/labstack/echo/v4 v4.8.0
github.com/labstack/gommon v0.3.1
github.com/spf13/cobra v1.5.0
)
47 changes: 45 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,13 +1,56 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/labstack/echo/v4 v4.8.0 h1:wdc6yKVaHxkNOEdz4cRZs1pQkwSXPiRjq69yWP4QQS8=
github.com/labstack/echo/v4 v4.8.0/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks=
github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=
github.com/labstack/gommon v0.3.1/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM=
github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs=
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52WA1u4=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ=
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b h1:1VkfZQv42XQlA/jchYumAnv1UPo6RgF9rJFkTgZIxO4=
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2YxUgyZ7EFOSLIcSSpiwE=
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
10 changes: 9 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package main

import (
"fmt"
"os"

"github.com/abhi-g80/chipku/cmd"
)

func main() {
cmd.Execute()
err := cmd.Execute()
if err != nil {
fmt.Printf("main: %v", err)
os.Exit(1)
}
os.Exit(0)
}
99 changes: 39 additions & 60 deletions server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"strings"
"text/template"

"github.com/gorilla/mux"
"github.com/labstack/echo/v4"
)

//go:embed static/index.html
Expand All @@ -38,6 +38,12 @@ func RandStringBytes(n int) string {
return string(b)
}

func store(v string) string {
hashVal := RandStringBytes(6)
chipkus[hashVal] = v
return hashVal
}

// IndexFileServer read the static html and return the http handler
func IndexFileServer() http.Handler {
fsys := fs.FS(index)
Expand All @@ -46,25 +52,17 @@ func IndexFileServer() http.Handler {
return http.FileServer(http.FS(html))
}

func store(v string) string {
hashVal := RandStringBytes(6)
chipkus[hashVal] = v
return hashVal
func version(c echo.Context) error {
return c.String(http.StatusOK, "Chipku v"+Version)
}

// DefaultHandler return the chipku version
func DefaultHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "chipku v%s", Version)
}

func getCodeTemplate(templ embed.FS) *template.Template {
func getCodeTemplate(templ embed.FS) (*template.Template, error) {
fsys := fs.FS(templ)
ts, err := template.ParseFS(fsys, "static/code.html.tmpl")
if err != nil {
ErrorLog.Println("could not load code template 😔")
ErrorLog.Printf("%s", err)
return nil, fmt.Errorf("could not template: %v", err)
}
return ts
return ts, nil
}

func enrichWithHTMLTags(codedata string, language string) CodeData {
Expand All @@ -77,63 +75,44 @@ func enrichWithHTMLTags(codedata string, language string) CodeData {
return CodeData{Code: z}
}

// FetchHandler GET handler function for fetching the code snippets
func FetchHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hashID, ok := vars["hashID"]
if !ok {
ErrorLog.Printf("something went wrong while fetching vars %v", vars)
return
}
split := strings.Split(hashID, ".")
id := split[0]
func fetchHandler(c echo.Context) error {
hashVal := c.Param("hashVal")
var lang string = "plaintext"
split := strings.Split(hashVal, ".")
id := split[0]
if len(split) > 1 {
lang = split[1]
}
if data, found := chipkus[id]; found {
_, ok := r.Header["No-Html"]
if ok {
w.Header().Add("Content-Type", "text; charset=UTF-8")
fmt.Fprintf(w, "%s", data)
return
}
ts := getCodeTemplate(codeTemplate)
enrichedData := enrichWithHTMLTags(data, lang)
err := ts.Execute(w, enrichedData)
if err != nil {
ErrorLog.Printf("something went wrong while templating code %s", err)
}
} else {
InfoLog.Printf("invalid id %s requested by %s", id, r.RemoteAddr)
fmt.Fprintf(w, "Invalid id %s provided :(", id)
data, found := chipkus[id]
if !found {
return c.String(http.StatusNotFound, "requested hash not found")
}
_, ok := c.Request().Header["No-Html"]
if ok {
c.Response().Header().Add("Content-Type", "text; charset=UTF-8")
return c.String(http.StatusOK, data)
}
ts, err := getCodeTemplate(codeTemplate)
if err != nil {
return err
}
enrichedData := enrichWithHTMLTags(data, lang)
return ts.Execute(c.Response().Writer, enrichedData)
}

// PastePostHandler POST handler func for managing snippets being posted via form
func PastePostHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
ErrorLog.Printf("ParseForm() err: %v", err)
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
value := r.FormValue("paste-area")
func pastePostHandler(c echo.Context) error {
value := c.FormValue("paste-area")
hashVal := store(value)
url := "/" + hashVal
InfoLog.Printf("new %s request from connection from %s", r.Method, r.RemoteAddr)
InfoLog.Printf("User-agent %s", r.UserAgent())
http.Redirect(w, r, url, http.StatusSeeOther)
return c.Redirect(http.StatusSeeOther, url)
}

// PastePutHandler PUT handler func for managing snippets sent via PUT
func PastePutHandler(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
func pastePutHandler(c echo.Context) error {
value, err := ioutil.ReadAll(c.Request().Body)
if err != nil {
ErrorLog.Printf("while reading body = %v", b)
return
return fmt.Errorf("while reading body: %v", err)
}
hashVal := store(string(b))
InfoLog.Printf("new %s request from connection from %s", r.Method, r.RemoteAddr)
InfoLog.Printf("User-agent %s", r.UserAgent())
fmt.Fprintf(w, "%s", hashVal)
hashVal := store(string(value))
c.Logger().Infof("responding %s", hashVal)
return c.String(http.StatusOK, hashVal)
}
Loading

0 comments on commit 0421109

Please sign in to comment.