github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/examples/gateway/main.go (about) 1 /* 2 Copyright [2014] - [2023] The Last.Backend authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "context" 21 "fmt" 22 "io" 23 "net/http" 24 "os" 25 26 "github.com/lastbackend/toolkit" 27 servicepb "github.com/lastbackend/toolkit/examples/gateway/gen/server" 28 typespb "github.com/lastbackend/toolkit/examples/helloworld/gen" 29 "github.com/lastbackend/toolkit/pkg/runtime" 30 ) 31 32 func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { 33 w.Header().Set("Content-Type", "application/json") 34 w.WriteHeader(http.StatusOK) 35 if _, err := io.WriteString(w, `{"alive": true}`); err != nil { 36 fmt.Println(err) 37 } 38 } 39 func main() { 40 // define service with name and options 41 app, err := servicepb.NewProxyGatewayService("gateway", 42 runtime.WithVersion("0.1.0"), 43 runtime.WithDescription("Example gateway microservice"), 44 runtime.WithEnvPrefix("GTW"), 45 ) 46 if err != nil { 47 fmt.Println(err) 48 } 49 50 // Add server 51 app.Server().HTTP().AddHandler(http.MethodGet, "/health", HealthCheckHandler) 52 53 app.Server().GRPC().SetService(newServer) 54 55 // Logger settings 56 app.Log().Info("Run microservice") 57 58 // Service run 59 if err := app.Start(context.Background()); err != nil { 60 app.Log().Errorf("could not run the service %v", err) 61 os.Exit(1) 62 return 63 } 64 65 app.Log().Info("graceful stop") 66 } 67 68 type Handlers struct { 69 app toolkit.Service 70 } 71 72 // Implement server 73 func newServer(app toolkit.Service) servicepb.ProxyGatewayRpcServer { 74 return &Handlers{ 75 app: app, 76 } 77 } 78 79 func (h *Handlers) HelloWorld(ctx context.Context, req *typespb.HelloRequest) (*typespb.HelloReply, error) { 80 return &typespb.HelloReply{ 81 Message: "hello", 82 }, nil 83 }