Skip to content

Commit

Permalink
rewrite heath checkup function
Browse files Browse the repository at this point in the history
Signed-off-by: viveksahu26 <vivekkumarsahu650@gmail.com>
  • Loading branch information
viveksahu26 committed Sep 15, 2022
1 parent 53b376e commit 0042824
Showing 1 changed file with 34 additions and 19 deletions.
53 changes: 34 additions & 19 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,50 @@ package main
import (
"fmt"
"net/http"
"os"

"github.com/viveksahu26/url_shortner/src"
)

func handleShortURL(writer http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
writer.WriteHeader(http.StatusMethodNotAllowed)
}
// get original URL from GET method by quering
originalURL := req.URL.Query().Get("longURL")
fmt.Println("originalURL: ", originalURL)
} else {
// get original URL from GET method by quering
originalURL := req.URL.Query().Get("longURL")
fmt.Println("originalURL: ", originalURL)

// generate random shortURL
shortURL := src.GenerateShortURL(originalURL)
fmt.Println("shortURL: ", shortURL)
// generate random shortURL
shortURL := src.GenerateShortURL(originalURL)
fmt.Println("shortURL: ", shortURL)

// save short and long URL to file
src.SaveInFile(shortURL, originalURL)
// save short and long URL to file
src.SaveInFile(shortURL, originalURL)

host := req.Host
host := req.Host

// build Response
resp := src.BuildURLWithResponse(host, shortURL, originalURL)
// build Response
resp := src.BuildURLWithResponse(host, shortURL, originalURL)

err := src.RespondWithJSON(writer, 200, resp)
if err != nil {
writer.Write([]byte("Failed to respond with JSON"))
err := src.RespondWithJSON(writer, 200, resp)
if err != nil {
writer.Write([]byte("<h1>Failed to respond with JSON</h1>"))
}
}
}

func healthCheckUp(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Health of Server is UP & Running..."))
if r.URL.Path != "/health" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}

if r.Method != "GET" {
http.Error(w, "Method other than GET not Supported...", http.StatusNotFound)
return
}

w.Write([]byte("<h1>Health of Server is UP & Running... !!</h1>"))
}

const addr = "localhost:8080"
Expand All @@ -54,8 +65,12 @@ func main() {
serveMux.HandleFunc("/sort-url", handleShortURL)

// healthCheckUp function mapped to /health
http.HandleFunc("/health", healthCheckUp)
serveMux.HandleFunc("/health", healthCheckUp)

// Server Listing on "localhost:8080"
srv.ListenAndServe()
err := srv.ListenAndServe()
if err != nil {
fmt.Println("Could not serve.")
os.Exit(1)
}
}

0 comments on commit 0042824

Please sign in to comment.