-
Notifications
You must be signed in to change notification settings - Fork 40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
code review for justforfunc episode #2
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
cfe88cb
remove unnecessary channel for graceful shutdown
campoy d46abed
simplified config package
campoy c4270c5
pass prefix to handler
campoy 355ccea
encapsulate handlers package better
campoy a2dcfb1
refactoring of the handlers package
campoy e684078
use singular names for packages
campoy ce3b5fe
refactor storage package
campoy 5c744cf
simplify encoding and rename to base62
campoy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package base62 | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
) | ||
|
||
// All characters | ||
const ( | ||
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | ||
length = int64(len(alphabet)) | ||
) | ||
|
||
// Encode number to base62. | ||
func Encode(n int64) string { | ||
if n == 0 { | ||
return string(alphabet[0]) | ||
} | ||
|
||
s := "" | ||
for ; n > 0; n = n / length { | ||
s = string(alphabet[n%length]) + s | ||
} | ||
return s | ||
} | ||
|
||
// Decode converts a base62 token to int. | ||
func Decode(key string) (int64, error) { | ||
var n int64 | ||
for _, c := range []byte(key) { | ||
i := strings.IndexByte(alphabet, c) | ||
if i < 0 { | ||
return 0, fmt.Errorf("unexpected character %c in base62 literal", c) | ||
} | ||
n = length*n + int64(i) | ||
} | ||
return n, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
// Package handlers provides HTTP request handlers. | ||
package handler | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"log" | ||
"net/http" | ||
"strings" | ||
|
||
"github.com/douglasmakey/ursho/storage" | ||
) | ||
|
||
// New returns an http handler for the url shortener. | ||
func New(prefix string, storage storage.Service) http.Handler { | ||
mux := http.NewServeMux() | ||
h := handler{prefix, storage} | ||
mux.HandleFunc("/encode/", responseHandler(h.encode)) | ||
mux.HandleFunc("/", h.redirect) | ||
mux.HandleFunc("/info/", responseHandler(h.decode)) | ||
return mux | ||
} | ||
|
||
type response struct { | ||
Success bool `json:"success"` | ||
Data interface{} `json:"response"` | ||
} | ||
|
||
type handler struct { | ||
prefix string | ||
storage storage.Service | ||
} | ||
|
||
func responseHandler(h func(io.Writer, *http.Request) (interface{}, int, error)) http.HandlerFunc { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
data, status, err := h(w, r) | ||
if err != nil { | ||
data = err.Error() | ||
} | ||
w.WriteHeader(status) | ||
w.Header().Set("Content-Type", "application/json") | ||
err = json.NewEncoder(w).Encode(response{Data: data, Success: err == nil}) | ||
if err != nil { | ||
log.Printf("could not encode response to output: %v", err) | ||
} | ||
} | ||
} | ||
|
||
func (h handler) encode(w io.Writer, r *http.Request) (interface{}, int, error) { | ||
if r.Method != http.MethodPost { | ||
return nil, http.StatusMethodNotAllowed, fmt.Errorf("method %s not allowed", r.Method) | ||
} | ||
|
||
var input struct{ URL string } | ||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil { | ||
return nil, http.StatusBadRequest, fmt.Errorf("Unable to decode JSON request body: %v", err) | ||
} | ||
|
||
url := strings.TrimSpace(input.URL) | ||
if url == "" { | ||
return nil, http.StatusBadRequest, fmt.Errorf("URL is empty") | ||
} | ||
|
||
c, err := h.storage.Save(url) | ||
if err != nil { | ||
return nil, http.StatusBadRequest, fmt.Errorf("Could not store in database: %v", err) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If database fails, it's not users fault. |
||
} | ||
|
||
return h.prefix + c, http.StatusCreated, nil | ||
} | ||
|
||
func (h handler) decode(w io.Writer, r *http.Request) (interface{}, int, error) { | ||
if r.Method != http.MethodGet { | ||
return nil, http.StatusMethodNotAllowed, fmt.Errorf("Method %s not allowed", r.Method) | ||
} | ||
|
||
code := r.URL.Path[len("/info/"):] | ||
|
||
model, err := h.storage.LoadInfo(code) | ||
if err != nil { | ||
return nil, http.StatusNotFound, fmt.Errorf("URL not found") | ||
} | ||
|
||
return model, http.StatusOK, nil | ||
} | ||
|
||
func (h handler) redirect(w http.ResponseWriter, r *http.Request) { | ||
if r.Method != http.MethodGet { | ||
w.WriteHeader(http.StatusMethodNotAllowed) | ||
return | ||
} | ||
code := r.URL.Path[len("/"):] | ||
|
||
model, err := h.storage.Load(code) | ||
if err != nil { | ||
w.WriteHeader(http.StatusNotFound) | ||
w.Write([]byte("URL Not Found")) | ||
return | ||
} | ||
|
||
http.Redirect(w, r, string(model.URL), http.StatusMovedPermanently) | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
shouldn't status become 500 if it fails to encode?