github.com/lastbackend/toolkit@v0.0.0-20241020043710-cafa37b95aad/examples/http/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 "github.com/lastbackend/toolkit/pkg/server/http/marshaler/jsonpb" 23 "google.golang.org/protobuf/encoding/protojson" 24 "io" 25 "net/http" 26 "os" 27 28 servicepb "github.com/lastbackend/toolkit/examples/http/gen/server" 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 40 func main() { 41 // define service with name and options 42 app, err := servicepb.NewHttpService("http", 43 runtime.WithVersion("0.1.0"), 44 runtime.WithDescription("Example http server"), 45 runtime.WithEnvPrefix("LB"), 46 ) 47 if err != nil { 48 fmt.Println(err) 49 } 50 51 // Register marshaller 52 jsonPb := &jsonpb.JSONPb{ 53 UnmarshalOptions: protojson.UnmarshalOptions{ 54 DiscardUnknown: true, 55 }, 56 } 57 58 if err = app.Server().HTTP().UseMarshaler("application/json", jsonPb); err != nil { 59 app.Log().Errorf("could not use json marshaler %v", err) 60 os.Exit(1) 61 return 62 } 63 64 // Add server 65 app.Server().HTTP().AddHandler(http.MethodGet, "/health", HealthCheckHandler) 66 67 // Logger settings 68 app.Log().Info("Run http server") 69 70 // Service run 71 if err := app.Start(context.Background()); err != nil { 72 app.Log().Errorf("could not run the service %v", err) 73 os.Exit(1) 74 return 75 } 76 77 app.Log().Info("graceful stop") 78 }