-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestExample.go
More file actions
79 lines (50 loc) · 1.21 KB
/
Copy pathrestExample.go
File metadata and controls
79 lines (50 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// go get ./...
package main
import (
"net/http"
"github.com/gorilla/mux"
"fmt"
"log"
"io/ioutil"
"sync"
)
var myData = make(map[string]string)
var mutex sync.Mutex
func main(){
router := mux.NewRouter()
router.HandleFunc("/{.*}", getValueByKey).Methods("GET")
router.HandleFunc("/{.*}", updateCreateKeyValue).Methods("PUT")
log.Fatal(http.ListenAndServe(":8000", router))
}
func updateCreateKeyValue(w http.ResponseWriter, r *http.Request){
w.Header().Set("Content-Type", "application/text")
vars := mux.Vars(r)
key := vars[".*"]
b, _ := ioutil.ReadAll(r.Body)
fmt.Println(key)
fmt.Println(string(b))
mutex.Lock()
if _, ok := myData[key]; ok{
myData[key] = string(b)
w.WriteHeader(http.StatusOK)
w.Write([]byte(myData[key]))
} else{
w.WriteHeader(http.StatusCreated)
myData[key] = string(b)
w.Write([] byte("Created"))
}
mutex.Unlock()
}
func getValueByKey(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
key := vars[".*"]
fmt.Println("Nandeshwar")
//jsonData,_ := json.Marshal(myData)
if value, ok := myData[key]; ok{
w.WriteHeader(http.StatusOK)
w.Write([]byte(value))
} else{
w.WriteHeader(http.StatusNotFound)
w.Write([] byte("Not Found"))
}
}