How to use newFeatureExplorerServer method of main Package

Best K6 code snippet using main.newFeatureExplorerServer

main.go

Source:main.go Github

copy

Full Screen

...58type featureExplorerServer struct {59 UnimplementedFeatureExplorerServer60 savedFeatures []*Feature // read-only after initialized61}62func newFeatureExplorerServer(features ...*Feature) *featureExplorerServer {63 return &featureExplorerServer{savedFeatures: features}64}65// GetFeature returns the feature at the given point.66func (s *featureExplorerServer) GetFeature(ctx context.Context, point *Point) (*Feature, error) {67 n := rand.Intn(1000)68 time.Sleep(time.Duration(n) * time.Millisecond)69 for _, feature := range s.savedFeatures {70 if proto.Equal(feature.Location, point) {71 return feature, nil72 }73 }74 // No feature was found, return an unnamed feature75 return &Feature{Location: point}, nil76}77// ListFeatures lists all features contained within the given bounding Rectangle.78func (s *featureExplorerServer) ListFeatures(rect *Rectangle, stream FeatureExplorer_ListFeaturesServer) error {79 for _, feature := range s.savedFeatures {80 if inRange(feature.Location, rect) {81 time.Sleep(500 * time.Millisecond)82 if err := stream.Send(feature); err != nil {83 return err84 }85 }86 }87 return nil88}89type routeGuideServer struct {90 UnimplementedRouteGuideServer91 savedFeatures []*Feature // read-only after initialized92 mu sync.Mutex // protects routeNotes93 routeNotes map[string][]*RouteNote94}95func newRouteGuideServer(features ...*Feature) *routeGuideServer {96 s := &routeGuideServer{97 savedFeatures: features,98 routeNotes: make(map[string][]*RouteNote),99 }100 return s101}102// RecordRoute records a route composited of a sequence of points.103//104// It gets a stream of points, and responds with statistics about the "trip":105// number of points, number of known features visited, total distance traveled, and106// total time spent.107func (s *routeGuideServer) RecordRoute(stream RouteGuide_RecordRouteServer) error {108 var pointCount, featureCount, distance int32109 var lastPoint *Point110 startTime := time.Now()111 for {112 point, err := stream.Recv()113 if err == io.EOF {114 endTime := time.Now()115 return stream.SendAndClose(&RouteSummary{116 PointCount: pointCount,117 FeatureCount: featureCount,118 Distance: distance,119 ElapsedTime: int32(endTime.Sub(startTime).Seconds()),120 })121 }122 if err != nil {123 return err124 }125 pointCount++126 for _, feature := range s.savedFeatures {127 if proto.Equal(feature.Location, point) {128 featureCount++129 }130 }131 if lastPoint != nil {132 distance += calcDistance(lastPoint, point)133 }134 lastPoint = point135 }136}137// RouteChat receives a stream of message/location pairs, and responds with a stream of all138// previous messages at each of those locations.139func (s *routeGuideServer) RouteChat(stream RouteGuide_RouteChatServer) error {140 for {141 in, err := stream.Recv()142 if err == io.EOF {143 return nil144 }145 if err != nil {146 return err147 }148 key := serialize(in.Location)149 s.mu.Lock()150 s.routeNotes[key] = append(s.routeNotes[key], in)151 // Note: this copy prevents blocking other clients while serving this one.152 // We don't need to do a deep copy, because elements in the slice are153 // insert-only and never modified.154 rn := make([]*RouteNote, len(s.routeNotes[key]))155 copy(rn, s.routeNotes[key])156 s.mu.Unlock()157 for _, note := range rn {158 if err := stream.Send(note); err != nil {159 return err160 }161 }162 }163}164// loadFeatures loads features from a JSON file.165func loadFeatures(filePath string) []*Feature {166 var data []byte167 if filePath != "" {168 var err error169 data, err = ioutil.ReadFile(filePath)170 if err != nil {171 log.Fatalf("Failed to load default features: %v", err)172 }173 } else {174 data = exampleData175 }176 var features []*Feature177 if err := json.Unmarshal(data, &features); err != nil {178 log.Fatalf("Failed to load default features: %v", err)179 }180 return features181}182func toRadians(num float64) float64 {183 return num * math.Pi / float64(180)184}185// calcDistance calculates the distance between two points using the "haversine" formula.186// The formula is based on http://mathforum.org/library/drmath/view/51879.html.187func calcDistance(p1 *Point, p2 *Point) int32 {188 const CordFactor float64 = 1e7189 const R = float64(6371000) // earth radius in metres190 lat1 := toRadians(float64(p1.Latitude) / CordFactor)191 lat2 := toRadians(float64(p2.Latitude) / CordFactor)192 lng1 := toRadians(float64(p1.Longitude) / CordFactor)193 lng2 := toRadians(float64(p2.Longitude) / CordFactor)194 dlat := lat2 - lat1195 dlng := lng2 - lng1196 a := math.Sin(dlat/2)*math.Sin(dlat/2) +197 math.Cos(lat1)*math.Cos(lat2)*198 math.Sin(dlng/2)*math.Sin(dlng/2)199 c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))200 distance := R * c201 return int32(distance)202}203func inRange(point *Point, rect *Rectangle) bool {204 left := math.Min(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude))205 right := math.Max(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude))206 top := math.Max(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude))207 bottom := math.Min(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude))208 if float64(point.Longitude) >= left &&209 float64(point.Longitude) <= right &&210 float64(point.Latitude) >= bottom &&211 float64(point.Latitude) <= top {212 return true213 }214 return false215}216func serialize(point *Point) string {217 return fmt.Sprintf("%d %d", point.Latitude, point.Longitude)218}219func main() {220 flag.Parse()221 lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))222 if err != nil {223 log.Fatalf("failed to listen: %v", err)224 }225 var opts []grpc.ServerOption226 if *tls {227 if *certFile == "" {228 *certFile = testdata.Path("server1.pem")229 }230 if *keyFile == "" {231 *keyFile = testdata.Path("server1.key")232 }233 creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)234 if err != nil {235 log.Fatalf("Failed to generate credentials %v", err)236 }237 opts = []grpc.ServerOption{grpc.Creds(creds)}238 }239 features := loadFeatures(*jsonDBFile)240 grpcServer := grpc.NewServer(opts...)241 RegisterRouteGuideServer(grpcServer, newRouteGuideServer(features...))242 RegisterFeatureExplorerServer(grpcServer, newFeatureExplorerServer(features...))243 reflection.Register(grpcServer)244 grpcServer.Serve(lis)245}246// exampleData is a copy of testdata/route_guide_db.json. It's to avoid247// specifying file path with `go run`.248var exampleData = []byte(`[{249 "location": {250 "latitude": 407838351,251 "longitude": -746143763252 },253 "name": "Patriots Path, Mendham, NJ 07945, USA"254}, {255 "location": {256 "latitude": 408122808,...

Full Screen

Full Screen

newFeatureExplorerServer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 lis, err := net.Listen("tcp", ":50051")4 if err != nil {5 log.Fatalf("failed to listen: %v", err)6 }7 s := newFeatureExplorerServer()8 grpcServer := grpc.NewServer()9 featureexplorer.RegisterFeatureExplorerServer(grpcServer, s)10 if err := grpcServer.Serve(lis); err != nil {11 log.Fatalf("failed to serve: %s", err)12 }13}14import (15func main() {16 conn, err := grpc.Dial(":50051", grpc.WithInsecure())17 if err != nil {18 log.Fatalf("did not connect: %v", err)19 }20 defer conn.Close()21 c := featureexplorer.NewFeatureExplorerClient(conn)22 r, err := c.GetFeature(context.Background(), &featureexplorer.Point{Latitude: 409146138, Longitude: -746188906})23 if err != nil {24 log.Fatalf("could not greet: %v", err)25 }26 log.Printf("Feature: %v", r)27}28import (29func main() {30 conn, err := grpc.Dial(":50051", grpc.WithInsecure())31 if err != nil {32 log.Fatalf("did not connect: %v", err)33 }34 defer conn.Close()35 c := featureexplorer.NewFeatureExplorerClient(conn)36 ctx, cancel := context.WithTimeout(context.Background(), time.Second)37 defer cancel()38 stream, err := c.ListFeatures(ctx, &featureexplorer.Rectangle{39 Lo: &featureexplorer.Point{Latitude: 400000000, Longitude: -750000000},40 Hi: &featureexplorer.Point{Latitude: 420000000, Longitude: -730000000},41 })42 if err != nil {43 log.Fatalf("could not greet: %v",

Full Screen

Full Screen

newFeatureExplorerServer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) != 2 {4 fmt.Println("Please provide port number as argument")5 os.Exit(1)6 }7 r := mux.NewRouter()8 r.HandleFunc("/features", newFeatureExplorerServer().handleFeatureExplorerRequest).Methods("GET")9 srv := &http.Server{

Full Screen

Full Screen

newFeatureExplorerServer

Using AI Code Generation

copy

Full Screen

1func main() {2 s := newFeatureExplorerServer()3 featureexplorer.RegisterFeatureExplorerServer(s.server, s)4 if err := s.server.Serve(s.listener); err != nil {5 log.Fatalf("failed to serve: %v", err)6 }7}8func newFeatureExplorerServer() *featureExplorerServer {9 listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))10 if err != nil {11 log.Fatalf("failed to listen: %v", err)12 }13 server := grpc.NewServer()14 return &featureExplorerServer{server: server, listener: listener}15}16func (s *featureExplorerServer) CreateFeature(ctx context.Context, req *featureexplorer.CreateFeatureRequest) (*featureexplorer.CreateFeatureResponse, error) {17 feature := req.GetFeature()18 name := feature.GetName()19 longitude := feature.GetLocation().GetLongitude()20 latitude := feature.GetLocation().GetLatitude()21 log.Printf("feature: name=%s, longitude=%f, latitude=%f", name, longitude, latitude)22 res := &featureexplorer.CreateFeatureResponse{}23}24func (s *featureExplorerServer) GetFeature(ctx context.Context, req *featureexplorer.GetFeatureRequest) (*featureexplorer.GetFeatureResponse, error) {25 name := req.GetName()26 log.Printf("feature: name=%s", name)27 feature := &featureexplorer.Feature{28 Location: &featureexplorer.Point{

Full Screen

Full Screen

newFeatureExplorerServer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 server := featureexplorer.NewFeatureExplorerServer()4 server.Start()5}6import (7type FeatureExplorerServer struct {

Full Screen

Full Screen

newFeatureExplorerServer

Using AI Code Generation

copy

Full Screen

1func main() {2 log.Fatal(http.ListenAndServe(":8080", newFeatureExplorerServer()))3}4func newFeatureExplorerServer() *FeatureExplorerServer {5 return &FeatureExplorerServer{}6}7func (s *FeatureExplorerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {8 fmt.Fprintf(w, "You've requested: %s\n", r.URL.Path)9}10func (s *FeatureExplorerServer) featureExplorerHandler(w http.ResponseWriter, r *http.Request) {11 fmt.Fprintf(w, "You've requested: %s\n", r.URL.Path)12}13func (s *FeatureExplorerServer) featureExplorerHandler(w http.ResponseWriter, r *http.Request) {14 fmt.Fprintf(w, "You've requested: %s\n", r.URL.Path)15 s.handleFeatureExplorer(w, r)16}17func (s *FeatureExplorerServer) handleFeatureExplorer(w http.ResponseWriter, r *http.Request) {18 fmt.Fprintf(w, "You've requested: %s\n", r.URL.Path)19 s.handleFeatureExplorer(w, r)20 s.handleFeatureExplorer(w, r)21}22func (

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful