Skip to content
This repository has been archived by the owner on Jun 15, 2022. It is now read-only.

Commit

Permalink
Add save endpoint
Browse files Browse the repository at this point in the history
Lock-Unlock removed from write function.
  • Loading branch information
gozeloglu committed Oct 16, 2021
1 parent 4fd3bd7 commit 9f09412
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
2 changes: 0 additions & 2 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,6 @@ func (k *Kvs) load() error {

// write saves data into file. It writes the data in map to the file.
func (k *Kvs) write() error {
k.mu.Lock()
defer k.mu.Unlock()
d := ""
for key, val := range k.kv {
d += fmt.Sprintf("%s=%s\n", key, val)
Expand Down
33 changes: 33 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ func (k *Kvs) Open() {
log.Printf("Kvs server running on %s...", k.addr)
http.HandleFunc("/set", k.set)
http.HandleFunc("/get/", k.get)
http.HandleFunc("/save", k.save)
log.Fatal(http.ListenAndServe(k.addr, nil))
}

Expand Down Expand Up @@ -136,3 +137,35 @@ func (k *Kvs) get(w http.ResponseWriter, r *http.Request) {
w.Write(j)
log.Printf("%s=%s", key, value)
}

func (k *Kvs) save(w http.ResponseWriter, r *http.Request) {
k.mu.Lock()
defer k.mu.Unlock()
if r.Method != http.MethodPut {
err := fmt.Sprintf("Wrong HTTP request. You need to send PUT request.")
log.Printf(err)
http.Error(w, err, http.StatusBadRequest)
return
}

err := k.write()
if err != nil {
log.Printf(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

resp := Response{
Result: "Saved",
}
j, err := json.Marshal(resp)
if err != nil {
log.Printf(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(headerContent, contentValue)
w.WriteHeader(http.StatusOK)
w.Write(j)
log.Printf("Saved.")
}

0 comments on commit 9f09412

Please sign in to comment.