From b80d38e7a5173fd2126ab01b8412fa871cb43dca Mon Sep 17 00:00:00 2001 From: Ryan Mehri Date: Sat, 9 May 2020 16:50:38 -0600 Subject: Add get hash endpoint --- api/api.go | 1 + api/routes.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) (limited to 'api') diff --git a/api/api.go b/api/api.go index 81ee0a0..e6372e7 100644 --- a/api/api.go +++ b/api/api.go @@ -31,6 +31,7 @@ func Serve(port int) { r := mux.NewRouter() r.HandleFunc("/health", healthCheckFunc) r.HandleFunc("/api", insertFunc).Methods("POST") + r.HandleFunc("/{hash}", getHashFunc).Methods("GET") http.Handle("/", r) diff --git a/api/routes.go b/api/routes.go index 103de04..ee166c2 100644 --- a/api/routes.go +++ b/api/routes.go @@ -1,8 +1,13 @@ package api +import "C" import ( + "encoding/json" "fmt" + "github.com/gorilla/mux" + "github.com/jackyzha0/ctrl-v/cache" "net/http" + "time" "github.com/jackyzha0/ctrl-v/db" @@ -29,3 +34,24 @@ func insertFunc(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "got err: %s", err.Error()) } } + +func getHashFunc(w http.ResponseWriter, r *http.Request) { + hash := mux.Vars(r)["hash"] + paste, err := cache.C.Get(hash) + + // if hash was not found + if err != nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprintf(w, "got err: %s", err.Error()) + return + } + + // otherwise, return paste content and current time + w.Header().Set("Content-Type", "application/json") + pasteMap := map[string]interface{} { + "Timestamp": time.Now(), + "Content": paste.Content, + } + jsonData, _ := json.Marshal(pasteMap) + fmt.Fprintf(w, "%+v", string(jsonData)) +} -- cgit v1.2.3