-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyserver.go
65 lines (58 loc) · 1.45 KB
/
myserver.go
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
65
package main
import (
"flag"
"fmt"
"net/http"
"strconv"
"sync/atomic"
)
var v int64
func addHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
nv := atomic.AddInt64(&v, 1)
fmt.Fprintf(w, "Value v = %d", nv)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
}
func decHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
nv := atomic.AddInt64(&v, -1)
fmt.Fprintf(w, "Value v = %d", nv)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
}
func resHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
nv := atomic.LoadInt64(&v)
fmt.Fprintf(w, "Value v = %d", nv)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
}
func setHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
sval := r.URL.Query().Get("value")
val, err := strconv.ParseInt(sval, 10, 64)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid value argument: %v", err)
return
}
atomic.StoreInt64(&v, val)
return
}
w.WriteHeader(http.StatusMethodNotAllowed)
}
func main() {
numPtr := flag.Int64("i", 0, "an int64 value v")
portPtr := flag.String("p", ":8080", "port number, string value")
flag.Parse()
v = *numPtr
http.HandleFunc("/add", addHandler)
http.HandleFunc("/dec", decHandler)
http.HandleFunc("/result", resHandler)
http.HandleFunc("/set", setHandler)
http.ListenAndServe(*portPtr, nil)
}