-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (37 loc) · 1.1 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 (
"net/http"
spinhttp "github.com/fermyon/spin/sdk/go/http"
"github.com/go_spin/message"
"github.com/mailru/easyjson"
)
func init() {
spinhttp.Handle(func(w http.ResponseWriter, r *http.Request) {
router := spinhttp.NewRouter()
router.GET("/", get_greeting)
router.POST("/", post_echo)
router.ServeHTTP(w, r)
})
}
func get_greeting(w http.ResponseWriter, r *http.Request, ps spinhttp.Params) {
m := &message.Message{Text: "Hello, World!"}
w.Header().Set("Content-Type", "application/json")
easyjson.MarshalToHTTPResponseWriter(m, w)
}
func post_echo(w http.ResponseWriter, r *http.Request, ps spinhttp.Params) {
m := &message.Message{}
// Read key "text" from body
err := easyjson.UnmarshalFromReader(r.Body, m)
if len(m.Text) == 0 {
w.Header().Set("Content-Type", "text/plain")
http.Error(w, "Missing key 'text' in request body", http.StatusUnprocessableEntity)
return
}
if err == nil {
w.Header().Set("Content-Type", "application/json")
m = &message.Message{Text: m.Text + " ECHO"}
easyjson.MarshalToHTTPResponseWriter(m, w)
return
}
}
func main() {}