-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmux.go
74 lines (54 loc) · 1.39 KB
/
gmux.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
68
69
70
71
72
73
74
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"encoding/json"
"github.com/gorilla/mux"
)
const port = ":8100"
var Info *log.Logger = log.New(os.Stdout,
"INFO: ",
log.Ldate|log.Ltime)
// The data model to be sent
type Response struct {
Message string
Code int
}
// hello world, the web server
func HomeGET(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
data := []Response{Response{"Hello GET", 200}}
b, _ := json.Marshal(data)
Info.Println("Sending response", string(b))
io.WriteString(w, string(b))
}
// hello world, the web server
func HomePOST(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
fmt.Fprintf(os.Stdout, "Post from website! req.PostFrom = %v\n", req.PostForm)
Info.Println("Post from website from", req.PostForm)
data := []Response{Response{"Hello POST", 200}}
b, _ := json.Marshal(data)
Info.Println("Sending response", string(b))
io.WriteString(w, string(b))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeGET).Methods("GET")
r.HandleFunc("/", HomePOST).Methods("POST")
fmt.Println("The router is running at", port)
http.Handle("/", r)
err := http.ListenAndServe(port, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "An Error has ocurred: %s\n", err)
}
}