-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (39 loc) · 1.12 KB
/
main.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/golang/protobuf/proto"
"github.com/ingojaeckel/golang-demo-protobuf"
)
func main() {
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
handlePost(w, r)
} else {
w.WriteHeader(415)
}
})
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
fmt.Println("running")
http.ListenAndServe(":8080", nil)
}
func handlePost(w http.ResponseWriter, r *http.Request) {
bytes, _ := ioutil.ReadAll(r.Body)
var someRequest messages.SomeRequest
if err := proto.Unmarshal(bytes, &someRequest); err != nil {
v := err.Error()
sendBytes(w, 400, messages.SomeResponse{Value: &v})
return
}
fmt.Printf("Request: %v\n", someRequest.GetParam())
v := "success"
sendBytes(w, 200, messages.SomeResponse{Value: &v})
}
func sendBytes(w http.ResponseWriter, status int, resp messages.SomeResponse) {
respBytes, _ := proto.Marshal(&resp)
fmt.Printf("Response: %v\n", respBytes)
w.WriteHeader(status)
w.Header().Add("Content-Type", "application/octet-stream")
w.Write(respBytes)
}