func redirectHandler(db database.DB) http.Handler { handler := func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "GET only", http.StatusMethodNotAllowed) return } shorturl := r.URL.Path[len(redirectPath):] if shorturl == "" { // display usage usage, err := ioutil.ReadFile("usage.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } writeLogErr(w, usage) return } url, err := db.Decode(shorturl) if err, ok := err.(database.ErrNotFound); ok { http.Error(w, err.Error(), http.StatusNotFound) return } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, string(url), 301) } return http.HandlerFunc(handler) }
func decodeHandler(db database.DB) http.Handler { handler := func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "use GET to decode urls", http.StatusMethodNotAllowed) return } shorturl := r.URL.Path[len(decodePath):] url, err := db.Decode(shorturl) if err, ok := err.(database.ErrNotFound); ok { http.Error(w, err.Error(), http.StatusNotFound) return } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } writeLogErr(w, []byte(url)) } return http.HandlerFunc(handler) }