-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgreeter.go
More file actions
57 lines (43 loc) · 1.12 KB
/
greeter.go
File metadata and controls
57 lines (43 loc) · 1.12 KB
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
package greeter
import (
"bytes"
"context"
"encoding/json"
"net/http"
"github.com/twitchtv/twirp"
pb "github.com/firstthumb/twirp-gcloud-greeter/proto"
)
type server struct{}
func (s *server) Greet(ctx context.Context, req *pb.GreetRequest) (*pb.GreetResponse, error) {
if req.Name == "" {
return nil, twirp.RequiredArgumentError("name")
}
return &pb.GreetResponse{Greeting: "Hello, " + req.Name + "!"}, nil
}
var mux = NewMux()
func Greeter(w http.ResponseWriter, r *http.Request) {
mux.ServeHTTP(w, r)
}
func NewMux() *http.ServeMux {
s := &server{}
twirpHandler := pb.NewGreeterServer(s, nil)
mux := http.NewServeMux()
mux.HandleFunc("/health", HealthCheck)
mux.Handle(twirpHandler.PathPrefix(), twirpHandler)
return mux
}
func HealthCheck(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
body, err := json.Marshal(map[string]interface{}{
"message": "OK",
})
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
}
json.HTMLEscape(&buf, body)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(buf.Bytes())
}