-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
67 lines (50 loc) · 1.2 KB
/
server.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
66
67
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
)
const (
PORT = 8090
)
var value int
type response struct {
Payload *payload `json:"payload"`
Success bool `json:"success"`
Error string `json:"error"`
}
type payload struct {
Value int `json:"value"`
}
func getValue(w http.ResponseWriter, r *http.Request) {
rsp := response{
Payload: &payload{
Value: value,
},
Success: true,
Error: "",
}
json.NewEncoder(w).Encode(rsp)
}
func setValue(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
number := vars["number"]
value, _ = strconv.Atoi(number)
json.NewEncoder(w).Encode(value)
}
func main() {
fmt.Printf("Running server on port: %d", PORT)
app := new(application)
app.auth.basic.username = os.Getenv("AUTH_USERNAME")
app.auth.basic.password = os.Getenv("AUTH_PASSWORD")
app.auth.bearer.token = os.Getenv("AUTH_TOKEN")
r := mux.NewRouter()
r.HandleFunc("/api/value", getValue).Methods("GET")
r.HandleFunc("/api/value/{number:[0-9]+}", setValue).Methods("POST")
r.HandleFunc("/api/basic/value", app.basicAuth(getValue)).Methods("GET")
http.Handle("/", r)
http.ListenAndServe(fmt.Sprintf(":%d", PORT), nil)
}