├── .gitignore ├── Dockerfile ├── LICENSE ├── cmd └── serverd │ └── main.go ├── config.json ├── docker-compose.yml ├── glide.yaml ├── go.mod ├── go.sum ├── internal ├── base62 │ └── base62.go ├── config │ └── config.go ├── handler │ └── handler.go └── storage │ ├── postgres │ └── postgres.go │ ├── sqlite3 │ └── sqlite3.go │ └── storage.go ├── item.go └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | #My 27 | vendor 28 | .idea 29 | glide.lock -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang as builder 2 | 3 | ADD . /go/src/github.com/douglasmakey/ursho/ 4 | 5 | WORKDIR /go/src/github.com/douglasmakey/ursho/ 6 | 7 | COPY go.mod go.sum ./ 8 | RUN go mod download 9 | 10 | RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o ursho ./cmd/serverd 11 | 12 | FROM scratch 13 | 14 | ENV PORT 8080 15 | 16 | COPY --from=builder /go/src/github.com/douglasmakey/ursho/ursho /app/ 17 | ADD config.json /app/config.json 18 | 19 | WORKDIR /app 20 | 21 | CMD ["./ursho"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Douglas Makey Mendez Molero 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /cmd/serverd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "net/http" 9 | "os" 10 | "os/signal" 11 | "syscall" 12 | 13 | "github.com/douglasmakey/ursho/internal/config" 14 | "github.com/douglasmakey/ursho/internal/handler" 15 | "github.com/douglasmakey/ursho/internal/storage/postgres" 16 | ) 17 | 18 | func main() { 19 | configPath := flag.String("cfg", "config.json", "path of the cfg file") 20 | flag.Parse() 21 | 22 | // Read config 23 | cfg, err := config.FromFile(*configPath) 24 | if err != nil { 25 | log.Fatal(err) 26 | } 27 | 28 | // Set use storage, select [Postgres, Filesystem, Redis ...] 29 | svc, err := postgres.New(cfg.Postgres.Host, cfg.Postgres.Port, cfg.Postgres.User, cfg.Postgres.Password, cfg.Postgres.DB) 30 | if err != nil { 31 | log.Fatal(err) 32 | } 33 | defer svc.Close() 34 | 35 | // Create a server 36 | server := &http.Server{ 37 | Addr: fmt.Sprintf("%s:%s", cfg.Server.Host, cfg.Server.Port), 38 | Handler: handler.New(cfg.Options.Prefix, svc), 39 | } 40 | 41 | go func() { 42 | // Start server 43 | log.Printf("Starting HTTP Server. Listening at %q", server.Addr) 44 | if err := server.ListenAndServe(); err != http.ErrServerClosed { 45 | log.Fatalf("%v", err) 46 | } else { 47 | log.Println("Server closed!") 48 | } 49 | }() 50 | 51 | // Check for a closing signal 52 | // Graceful shutdown 53 | sigquit := make(chan os.Signal, 1) 54 | signal.Notify(sigquit, os.Interrupt, syscall.SIGTERM) 55 | 56 | sig := <-sigquit 57 | log.Printf("caught sig: %+v", sig) 58 | log.Printf("Gracefully shutting down server...") 59 | 60 | if err := server.Shutdown(context.Background()); err != nil { 61 | log.Printf("Unable to shut down server: %v", err) 62 | } else { 63 | log.Println("Server stopped") 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "server": { 3 | "host": "0.0.0.0", 4 | "port": "8080" 5 | }, 6 | "options": { 7 | "prefix": "http://localhost:8080/" 8 | }, 9 | "postgres": { 10 | "host": "app_postgres", 11 | "port": "5432", 12 | "user": "ursho_db", 13 | "password": "mypass", 14 | "db": "ursho_db" 15 | }, 16 | "sqlite": { 17 | "filepath": "path" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | ursho: 4 | restart: always 5 | build: . 6 | ports: 7 | - 8080:8080 8 | depends_on: 9 | - app_postgres 10 | app_postgres: 11 | image: postgres 12 | environment: 13 | POSTGRES_PASSWORD: 'mypass' 14 | POSTGRES_USER: 'ursho_db' 15 | POSTGRES_DB: 'ursho_db' 16 | ports: 17 | - 5432:5432 -------------------------------------------------------------------------------- /glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/douglasmakaey/ursho 2 | import: 3 | - package: github.com/lib/pq 4 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/douglasmakey/ursho 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/lib/pq v1.10.7 7 | github.com/mattn/go-sqlite3 v1.14.15 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= 2 | github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= 3 | github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI= 4 | github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= 5 | -------------------------------------------------------------------------------- /internal/base62/base62.go: -------------------------------------------------------------------------------- 1 | package base62 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | // All characters 9 | const ( 10 | alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 11 | length = int64(len(alphabet)) 12 | ) 13 | 14 | // Encode number to base62. 15 | func Encode(n int64) string { 16 | if n == 0 { 17 | return string(alphabet[0]) 18 | } 19 | 20 | s := "" 21 | for ; n > 0; n = n / length { 22 | s = string(alphabet[n%length]) + s 23 | } 24 | return s 25 | } 26 | 27 | // Decode converts a base62 token to int. 28 | func Decode(key string) (int64, error) { 29 | var n int64 30 | for _, c := range []byte(key) { 31 | i := strings.IndexByte(alphabet, c) 32 | if i < 0 { 33 | return 0, fmt.Errorf("unexpected character %c in base62 literal", c) 34 | } 35 | n = length*n + int64(i) 36 | } 37 | return n, nil 38 | } 39 | -------------------------------------------------------------------------------- /internal/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | ) 7 | 8 | // Config contains the configuration of the url shortener. 9 | type Config struct { 10 | Server struct { 11 | Host string `json:"host"` 12 | Port string `json:"port"` 13 | } `json:"server"` 14 | Redis struct { 15 | Host string `json:"host"` 16 | Password string `json:"password"` 17 | DB string `json:"db"` 18 | } `json:"redis"` 19 | Postgres struct { 20 | Host string `json:"host"` 21 | Port string `json:"port"` 22 | User string `json:"user"` 23 | Password string `json:"password"` 24 | DB string `json:"db"` 25 | } `json:"postgres"` 26 | Sqlite struct { 27 | FilePath string `json:"filepath"` 28 | } `json:"sqlite"` 29 | Options struct { 30 | Prefix string `json:"prefix"` 31 | } `json:"options"` 32 | } 33 | 34 | // FromFile returns a configuration parsed from the given file. 35 | func FromFile(path string) (*Config, error) { 36 | b, err := os.ReadFile(path) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | var cfg Config 42 | if err := json.Unmarshal(b, &cfg); err != nil { 43 | return nil, err 44 | } 45 | 46 | return &cfg, nil 47 | } 48 | -------------------------------------------------------------------------------- /internal/handler/handler.go: -------------------------------------------------------------------------------- 1 | // Package handlers provides HTTP request handlers. 2 | package handler 3 | 4 | import ( 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "log" 9 | "net/http" 10 | "strings" 11 | 12 | "github.com/douglasmakey/ursho" 13 | ) 14 | 15 | // New returns an http handler for the url shortener. 16 | func New(prefix string, storage ursho.ItemService) http.Handler { 17 | mux := http.NewServeMux() 18 | h := handler{prefix, storage} 19 | mux.HandleFunc("/encode/", responseHandler(h.encode)) 20 | mux.HandleFunc("/", h.redirect) 21 | mux.HandleFunc("/info/", responseHandler(h.decode)) 22 | return mux 23 | } 24 | 25 | type response struct { 26 | Success bool `json:"success"` 27 | Data interface{} `json:"response"` 28 | } 29 | 30 | type handler struct { 31 | prefix string 32 | storage ursho.ItemService 33 | } 34 | 35 | func responseHandler(h func(io.Writer, *http.Request) (interface{}, int, error)) http.HandlerFunc { 36 | return func(w http.ResponseWriter, r *http.Request) { 37 | data, status, err := h(w, r) 38 | if err != nil { 39 | data = err.Error() 40 | } 41 | w.Header().Set("Content-Type", "application/json") 42 | w.WriteHeader(status) 43 | err = json.NewEncoder(w).Encode(response{Data: data, Success: err == nil}) 44 | if err != nil { 45 | log.Printf("could not encode response to output: %v", err) 46 | } 47 | } 48 | } 49 | 50 | func (h handler) encode(w io.Writer, r *http.Request) (interface{}, int, error) { 51 | if r.Method != http.MethodPost { 52 | return nil, http.StatusMethodNotAllowed, fmt.Errorf("method %s not allowed", r.Method) 53 | } 54 | 55 | var input struct{ URL string } 56 | if err := json.NewDecoder(r.Body).Decode(&input); err != nil { 57 | return nil, http.StatusBadRequest, fmt.Errorf("unable to decode JSON request body: %v", err) 58 | } 59 | 60 | url := strings.TrimSpace(input.URL) 61 | if url == "" { 62 | return nil, http.StatusBadRequest, fmt.Errorf("URL is empty") 63 | } 64 | 65 | if !strings.Contains(url, "http") { 66 | url = "http://" + url 67 | } 68 | 69 | c, err := h.storage.Save(url) 70 | if err != nil { 71 | return nil, http.StatusInternalServerError, fmt.Errorf("could not store in database: %v", err) 72 | } 73 | 74 | return h.prefix + c, http.StatusCreated, nil 75 | } 76 | 77 | func (h handler) decode(w io.Writer, r *http.Request) (interface{}, int, error) { 78 | if r.Method != http.MethodGet { 79 | return nil, http.StatusMethodNotAllowed, fmt.Errorf("method %s not allowed", r.Method) 80 | } 81 | 82 | code := r.URL.Path[len("/info/"):] 83 | 84 | model, err := h.storage.LoadInfo(code) 85 | if err != nil { 86 | return nil, http.StatusNotFound, fmt.Errorf("URL not found") 87 | } 88 | 89 | return model, http.StatusOK, nil 90 | } 91 | 92 | func (h handler) redirect(w http.ResponseWriter, r *http.Request) { 93 | if r.Method != http.MethodGet { 94 | w.WriteHeader(http.StatusMethodNotAllowed) 95 | return 96 | } 97 | code := r.URL.Path[len("/"):] 98 | 99 | url, err := h.storage.Load(code) 100 | if err != nil { 101 | w.WriteHeader(http.StatusNotFound) 102 | w.Write([]byte("URL Not Found")) 103 | return 104 | } 105 | 106 | http.Redirect(w, r, url, http.StatusMovedPermanently) 107 | } 108 | -------------------------------------------------------------------------------- /internal/storage/postgres/postgres.go: -------------------------------------------------------------------------------- 1 | package postgres 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | 7 | "github.com/douglasmakey/ursho" 8 | "github.com/douglasmakey/ursho/internal/base62" 9 | 10 | // This loads the postgres drivers. 11 | _ "github.com/lib/pq" 12 | ) 13 | 14 | // New returns a postgres backed storage service. 15 | func New(host, port, user, password, dbName string) (ursho.ItemService, error) { 16 | // Connect postgres 17 | connect := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", 18 | host, port, user, password, dbName) 19 | 20 | db, err := sql.Open("postgres", connect) 21 | if err != nil { 22 | return nil, err 23 | } 24 | 25 | // Ping to connection 26 | err = db.Ping() 27 | if err != nil { 28 | return nil, err 29 | } 30 | 31 | // Create table if not exists 32 | strQuery := "CREATE TABLE IF NOT EXISTS shortener (uid serial NOT NULL, url VARCHAR not NULL, " + 33 | "visited boolean DEFAULT FALSE, count INTEGER DEFAULT 0);" 34 | 35 | _, err = db.Exec(strQuery) 36 | if err != nil { 37 | return nil, err 38 | } 39 | return &postgres{db}, nil 40 | } 41 | 42 | type postgres struct{ db *sql.DB } 43 | 44 | func (p *postgres) Save(url string) (string, error) { 45 | var id int64 46 | err := p.db.QueryRow("INSERT INTO shortener(url,visited,count) VALUES($1,$2,$3) returning uid;", url, false, 0).Scan(&id) 47 | if err != nil { 48 | return "", err 49 | } 50 | return base62.Encode(id), nil 51 | } 52 | 53 | func (p *postgres) Load(code string) (string, error) { 54 | id, err := base62.Decode(code) 55 | if err != nil { 56 | return "", err 57 | } 58 | 59 | var url string 60 | err = p.db.QueryRow("update shortener set visited=true, count = count + 1 where uid=$1 RETURNING url", id).Scan(&url) 61 | if err != nil { 62 | return "", err 63 | } 64 | return url, nil 65 | } 66 | 67 | func (p *postgres) LoadInfo(code string) (*ursho.Item, error) { 68 | id, err := base62.Decode(code) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | var item ursho.Item 74 | err = p.db.QueryRow("SELECT url, visited, count FROM shortener where uid=$1 limit 1", id). 75 | Scan(&item.URL, &item.Visited, &item.Count) 76 | if err != nil { 77 | return nil, err 78 | } 79 | 80 | return &item, nil 81 | } 82 | 83 | func (p *postgres) Close() error { return p.db.Close() } 84 | -------------------------------------------------------------------------------- /internal/storage/sqlite3/sqlite3.go: -------------------------------------------------------------------------------- 1 | package sqlite3 2 | 3 | import ( 4 | "database/sql" 5 | 6 | "github.com/douglasmakey/ursho" 7 | "github.com/douglasmakey/ursho/internal/base62" 8 | 9 | _ "github.com/mattn/go-sqlite3" // sqlite engine 10 | ) 11 | 12 | type sqlite3 struct { 13 | db *sql.DB 14 | } 15 | 16 | // New returns a sqlite backed storage service. 17 | func New(path string) (ursho.ItemService, error) { 18 | db, err := sql.Open("sqlite3", path) 19 | if err != nil { 20 | return nil, err 21 | } 22 | 23 | // Create table if not exists 24 | strQuery := "CREATE TABLE IF NOT EXISTS shortener (uid INTEGER PRIMARY KEY AUTOINCREMENT, url VARCHAR not NULL, " + 25 | "visited boolean DEFAULT FALSE, count INTEGER DEFAULT 0);" 26 | _, err = db.Exec(strQuery) 27 | if err != nil { 28 | return nil, err 29 | } 30 | 31 | return &sqlite3{db: db}, nil 32 | } 33 | 34 | func (s *sqlite3) Save(url string) (string, error) { 35 | var id int64 36 | 37 | stmt, err := s.db.Prepare("INSERT INTO shortener(url,visited,count) VALUES(?, ?, ?)") 38 | if err != nil { 39 | return "", err 40 | } 41 | 42 | res, err := stmt.Exec(url, 0, 0) 43 | if err != nil { 44 | return "", err 45 | } 46 | 47 | id, err = res.LastInsertId() 48 | if err != nil { 49 | return "", err 50 | } 51 | 52 | return base62.Encode(id), nil 53 | } 54 | 55 | func (s *sqlite3) Load(code string) (string, error) { 56 | id, err := base62.Decode(code) 57 | if err != nil { 58 | return "", err 59 | } 60 | 61 | var url string 62 | err = s.db.QueryRow("update shortener set visited=true, count = count + 1 where uid=$1 RETURNING url", id).Scan(&url) 63 | if err != nil { 64 | return "", err 65 | } 66 | 67 | return url, nil 68 | } 69 | 70 | func (s *sqlite3) LoadInfo(code string) (*ursho.Item, error) { 71 | id, err := base62.Decode(code) 72 | if err != nil { 73 | return nil, err 74 | } 75 | 76 | var item ursho.Item 77 | query := "SELECT url, visited, count FROM shortener where uid=$1 limit 1" 78 | err = s.db.QueryRow(query, id).Scan(&item.URL, &item.Visited, &item.Count) 79 | if err != nil { 80 | return nil, err 81 | } 82 | 83 | return &item, nil 84 | } 85 | 86 | func (s *sqlite3) Close() error { return s.db.Close() } 87 | -------------------------------------------------------------------------------- /internal/storage/storage.go: -------------------------------------------------------------------------------- 1 | package storage 2 | -------------------------------------------------------------------------------- /item.go: -------------------------------------------------------------------------------- 1 | package ursho 2 | 3 | type Item struct { 4 | URL string `json:"url"` 5 | Visited bool `json:"visited"` 6 | Count int `json:"count"` 7 | } 8 | 9 | type ItemService interface { 10 | Save(string) (string, error) 11 | Load(string) (string, error) 12 | LoadInfo(string) (*Item, error) 13 | Close() error 14 | } 15 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Synopsis 2 | 3 | #### URL Shortener Service 4 | 5 | ## Run 6 | 7 | Run with Docker 8 | 9 | ```bash 10 | docker-compose up 11 | ``` 12 | 13 | ## Code Example 14 | Using CURL 15 | Generate shortener\ 16 | ``` 17 | $ curl -H "Content-Type: application/json" -X POST -d '{"url":"www.google.com"}' http://localhost:8080/encode/ 18 | 19 | 20 | ``` 21 | 22 | Redirect 23 | Open url in your browser [http://localhost:8080/bN](http://localhost:8080/1) 24 | 25 | OR 26 | ```$ 27 | curl http://localhost:8080/1 28 | ``` 29 | 30 | Get info for url shortener\ 31 | `curl http://localhost:8080/info/1 ` 32 | 33 | Response: 34 | ```json 35 | { 36 | "success":true, 37 | "response": { 38 | "url":"www.google.com", 39 | "visited":true, 40 | "count":1 41 | } 42 | } 43 | ``` 44 | 45 | ## Motivation 46 | 47 | .. 48 | 49 | ## Installation 50 | 51 | You can install it using 'go get' or cloning the repository. 52 | 53 | #### Use go get 54 | ``` 55 | # fetches the program 56 | go get github.com/douglasmakey/ursho 57 | 58 | # move to the app's directory 59 | cd $GOPATH/src/github.com/douglasmakey/ursho 60 | ``` 61 | #### Cloning the repo 62 | We'll use github.com/user as our base path. Create a directory inside your workspace in which to keep source code: 63 | 64 | ***mkdir -p $GOPATH/src/github.com/douglasmakey cd "$_"*** 65 | 66 | Clone repository or download and unrar in folder\ 67 | ```git clone https://github.com/douglasmakey/ursho.git``` 68 | 69 | 70 | Use GLIDE Package Management for Golang, for installation all packages 71 | 72 | https://github.com/Masterminds/glide 73 | 74 | Run `glide install` in the folder. 75 | 76 | #### Select method of persistence 77 | select the method of persistence, in which you going to work.\ 78 | `storage := &storages.Postgres{}` 79 | 80 | If selected Postgresql as Storage, create database 81 | ```sql 82 | CREATE DATABASE ursho_db; 83 | ``` 84 | 85 | 86 | Add your config for the method of persistence and other options in file config.json\ 87 | ```json 88 | { 89 | "server": { 90 | "host": "0.0.0.0", 91 | "port": "8080" 92 | }, 93 | "options": { 94 | "prefix": "http://localhost:8080/" 95 | }, 96 | "posgres": { 97 | "user": "postgres", 98 | "password": "mysecretpassword", 99 | "db": "ursho_db" 100 | } 101 | } 102 | ``` 103 | ## API Reference 104 | 105 | .. 106 | 107 | ## Tests 108 | 109 | .. 110 | 111 | ## Contributors 112 | 113 | .. 114 | 115 | ## License 116 | 117 | A short snippet describing the license (MIT, Apache, etc.) 118 | --------------------------------------------------------------------------------