| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"expvar" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"io/ioutil" |
| 8 |
"net/http" |
| 9 |
"strings" |
| 10 |
"sync" |
| 11 |
"time" |
| 12 |
|
| 13 |
"github.com/paulbellamy/ratecounter" |
| 14 |
) |
| 15 |
|
| 16 |
var ( |
| 17 |
counter *ratecounter.RateCounter |
| 18 |
hitspersecond = expvar.NewInt("hits_per_second") |
| 19 |
mu sync.Mutex |
| 20 |
m sync.Mutex |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
func Query(w http.ResponseWriter, req *http.Request) { |
| 25 |
io.WriteString(w, "du") |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
func Count(w http.ResponseWriter, req *http.Request) { |
| 30 |
io.WriteString(w, fmt.Sprintf("%v", linecount)) |
| 31 |
} |
| 32 |
|
| 33 |
var n int |
| 34 |
var linecount int |
| 35 |
|
| 36 |
|
| 37 |
func Write(w http.ResponseWriter, req *http.Request) { |
| 38 |
mu.Lock() |
| 39 |
n++ |
| 40 |
mu.Unlock() |
| 41 |
|
| 42 |
counter.Incr(1) |
| 43 |
hitspersecond.Set(counter.Rate()) |
| 44 |
w.WriteHeader(http.StatusNoContent) |
| 45 |
fmt.Printf("Reqests Per Second: %v\n", hitspersecond) |
| 46 |
fmt.Printf("Count: %v\n", n) |
| 47 |
|
| 48 |
content, _ := ioutil.ReadAll(req.Body) |
| 49 |
m.Lock() |
| 50 |
arr := strings.Split(string(content), "\n") |
| 51 |
linecount += len(arr) |
| 52 |
m.Unlock() |
| 53 |
|
| 54 |
fmt.Printf("Line Count: %v\n\n", linecount) |
| 55 |
} |
| 56 |
|
| 57 |
func init() { |
| 58 |
n = 0 |
| 59 |
linecount = 0 |
| 60 |
counter = ratecounter.NewRateCounter(1 * time.Second) |
| 61 |
} |
| 62 |
|
| 63 |
func main() { |
| 64 |
mux := http.NewServeMux() |
| 65 |
mux.HandleFunc("/query", Query) |
| 66 |
mux.HandleFunc("/write", Write) |
| 67 |
mux.HandleFunc("/count", Count) |
| 68 |
|
| 69 |
err := http.ListenAndServe(":1234", mux) |
| 70 |
if err != nil { |
| 71 |
fmt.Println("Fatal") |
| 72 |
} |
| 73 |
|
| 74 |
} |