How to use ParseDirection method of stream Package

Best Toxiproxy code snippet using stream.ParseDirection

server.go

Source:server.go Github

copy

Full Screen

1package server2import (3 "context"4 "errors"5 "log"6 "sync"7 "time"8 "github.com/MatteSoder/pong/pb"9 "github.com/MatteSoder/pong/pkg/entities"10 "github.com/MatteSoder/pong/pkg/game"11 "github.com/google/uuid"12 "google.golang.org/grpc/metadata"13)14const (15 // Client timeout in minutes16 clientTimeout = 1517 // Maximum number of clients allowed18 maxClients = 219)20// GameServer is used to stream game information with clients.21type GameServer struct {22 pb.UnimplementedGameServiceServer23 pong game.Pong24 clients map[uuid.UUID]*client25 mu sync.RWMutex26}27// NewGameServer constructs a new game server struct.28func NewGameServer(pong game.Pong) *GameServer {29 server := &GameServer{30 pong: pong,31 clients: make(map[uuid.UUID]*client),32 }33 // Start listening for changes34 server.changeListener()35 // Start listening for client timeout36 server.timeoutListener()37 return server38}39// Stream is the main loop for dealing with individual players.40func (s *GameServer) Stream(srv pb.GameService_StreamServer) error {41 ctx := srv.Context()42 client, err := s.extractClientFromContext(ctx)43 if err != nil {44 return err45 }46 if client.streamServer != nil {47 return errors.New("stream already active")48 }49 client.streamServer = srv50 // Wait for stream requests.51 go func() {52 for {53 req, err := srv.Recv()54 if err != nil {55 client.done <- errors.New("failed to receive request")56 return57 }58 // Update client's last interaction59 client.activeTime = time.Now()60 // Get the action61 switch req.GetAction().(type) {62 case *pb.StreamRequest_Move:63 s.handleMoveRequest(req, client)64 }65 }66 }()67 // Wait for stream to be done.68 var doneError error69 select {70 case <-ctx.Done():71 doneError = ctx.Err()72 case doneError = <-client.done:73 }74 log.Printf(`stream done with error "%v"`, doneError)75 log.Printf("%s - removing client", client.id)76 // Remove client77 s.removeClient(client.id)78 return doneError79}80func (s *GameServer) Connect(ctx context.Context, req *pb.ConnectRequest) (*pb.ConnectResponse, error) {81 if len(s.clients) >= maxClients {82 return nil, errors.New("server is full")83 }84 playerID, err := uuid.Parse(req.Id)85 if err != nil {86 return nil, err87 }88 // Check if player already exists.89 if s.pong.GetPlayer(playerID) != nil {90 return nil, errors.New("duplicate player ID provided")91 }92 // Determine the position of the player based on the number of players.93 startPos := entities.Coordinate{X: .9, Y: 0}94 if len(s.clients) == 1 {95 startPos = entities.Coordinate{X: -.9, Y: 0}96 }97 player := &entities.Player{98 Entity: entities.NewBaseEntity(playerID, startPos),99 }100 // Add player to game101 s.pong.AddEntity(player)102 // Inform all other clients of the new player.103 resp := pb.StreamResponse{104 Action: &pb.StreamResponse_AddEntity{105 AddEntity: &pb.AddEntity{Entity: parseEntity(player)},106 },107 }108 s.broadcast(&resp)109 // Add the new client.110 s.mu.Lock()111 // Generate a new client identifier112 clientID := uuid.New()113 s.clients[clientID] = &client{114 id: clientID,115 playerID: playerID,116 done: make(chan error),117 activeTime: time.Now(),118 }119 s.mu.Unlock()120 log.Printf("Connected with client: %v", s.clients[clientID])121 // Get all the entities from the game and return122 entities := make([]*pb.Entity, 0)123 for _, e := range s.pong.GetEntities() {124 // Parse the domain entity125 entity := parseEntity(e)126 // Add entity to slice127 if entity != nil {128 entities = append(entities, entity)129 }130 }131 // Return with the new entities132 return &pb.ConnectResponse{133 ClientId: clientID.String(),134 Entities: entities,135 }, nil136}137// extractClientFromContext retrieves the client from the context with the matching client identifier.138func (s *GameServer) extractClientFromContext(ctx context.Context) (*client, error) {139 // Extract the headers from the incoming message140 headers, _ := metadata.FromIncomingContext(ctx)141 // Get the client ideitifier142 clientIdRaw := headers["client_id"]143 if len(clientIdRaw) == 0 {144 return nil, errors.New("no cliennt id provided")145 }146 clientId, err := uuid.Parse(clientIdRaw[0])147 if err != nil {148 return nil, errors.New("cannot parse client id")149 }150 s.mu.RLock()151 defer s.mu.RUnlock()152 client, ok := s.clients[clientId]153 if !ok {154 return nil, errors.New("client id not recognized")155 }156 // Return with the client157 return client, nil158}159func (s *GameServer) timeoutListener() {160 timeoutTicker := time.NewTicker(1 * time.Minute)161 go func() {162 for {163 for _, client := range s.clients {164 // Check time since the last interaction from the client.165 if time.Since(client.activeTime).Minutes() > clientTimeout {166 // Inform the client that of timeout167 client.done <- errors.New("you have been timed out")168 return169 }170 }171 <-timeoutTicker.C172 }173 }()174}175func (s *GameServer) changeListener() {176 go func() {177 for {178 change := <-s.pong.ChangeListener()179 // Update game based on the change180 switch t := change.(type) {181 case game.MoveChange:182 s.handleMoveChange(t)183 }184 }185 }()186}187func (s *GameServer) handleMoveChange(change game.MoveChange) {188 resp := pb.StreamResponse{189 Action: &pb.StreamResponse_UpdateEntity{190 UpdateEntity: &pb.UpdateEntity{191 Entity: parseEntity(change.Entity),192 },193 },194 }195 s.broadcast(&resp)196}197func (s *GameServer) handleMoveRequest(req *pb.StreamRequest, client *client) {198 move := req.GetMove()199 s.pong.ActionChannel() <- game.MoveAction{200 ID: client.playerID,201 Direction: parseDirection(move.Direction),202 Created: time.Now(),203 }204}205// broadcast sends a response to all clients.206func (s *GameServer) broadcast(resp *pb.StreamResponse) {207 s.mu.Lock()208 for id, client := range s.clients {209 if client.streamServer == nil {210 continue211 }212 if err := client.streamServer.Send(resp); err != nil {213 log.Printf("%s - broadcast error %v", id, err)214 client.done <- errors.New("failed to broadcast message")215 continue216 }217 log.Printf("%s - broadcasted %+v", resp, id)218 }219 s.mu.Unlock()220}221func (s *GameServer) removeClient(id uuid.UUID) {222 s.mu.Lock()223 delete(s.clients, id)224 s.mu.Unlock()225}226/// parseEntity maps the domain entity into the protobuf entity227func parseEntity(entity entities.Entity) *pb.Entity {228 switch e := entity.(type) {229 case *entities.Player:230 // Parse the domain entity into protobuf231 pbPlayer := pb.Entity_Player{232 Player: parsePlayer(e),233 }234 // Return the entity235 return &pb.Entity{Entity: &pbPlayer}236 case *entities.Ball:237 // Parse the domain entity into protobuf238 pbBall := pb.Entity_Ball{239 Ball: parseBall(e),240 }241 // Return the entity242 return &pb.Entity{Entity: &pbBall}243 }244 log.Printf("cannot get proto entity for %T -> %+v", entity, entity)245 return nil246}247/// parsePlayer maps the domain Player entity into the protobuf Player model.248func parsePlayer(entity *entities.Player) *pb.Player {249 return &pb.Player{250 Id: entity.Id().String(),251 Position: &pb.Coordinate{252 X: float64(entity.Coordinate().X),253 Y: float64(entity.Coordinate().Y),254 },255 }256}257/// parseBall maps the domain Ball entity into the protobuf Ball model.258func parseBall(entity *entities.Ball) *pb.Ball {259 return &pb.Ball{260 Id: entity.Id().String(),261 Position: &pb.Coordinate{262 X: float64(entity.Coordinate().X),263 Y: float64(entity.Coordinate().Y),264 },265 }266}267func parseDirection(pbDir pb.Direction) entities.Direction {268 direction := entities.DirectionNONE269 switch pbDir {270 case pb.Direction_DIRECTION_UP:271 direction = entities.DirectionUP272 case pb.Direction_DIRECTION_DOWN:273 direction = entities.DirectionDOWN274 case pb.Direction_DIRECTION_LEFT:275 direction = entities.DirectionLEFT276 case pb.Direction_DIRECTION_RIGHT:277 direction = entities.DirectionRIGHT278 }279 return direction280}...

Full Screen

Full Screen

direction_test.go

Source:direction_test.go Github

copy

Full Screen

...26 }27 })28 }29}30func TestParseDirection(t *testing.T) {31 testCases := []struct {32 name string33 input string34 expected stream.Direction35 err error36 }{37 {"parse empty", "", stream.NumDirections, stream.ErrInvalidDirectionParameter},38 {"parse upstream", "upstream", stream.Upstream, nil},39 {"parse downstream", "downstream", stream.Downstream, nil},40 {"parse unknown", "unknown", stream.NumDirections, stream.ErrInvalidDirectionParameter},41 {"parse number", "-123", stream.NumDirections, stream.ErrInvalidDirectionParameter},42 {"parse upper case", "DOWNSTREAM", stream.Downstream, nil},43 {"parse camel case", "UpStream", stream.Upstream, nil},44 }45 for _, tc := range testCases {46 tc := tc // capture range variable47 t.Run(tc.name, func(t *testing.T) {48 t.Parallel()49 actual, err := stream.ParseDirection(tc.input)50 if actual != tc.expected {51 t.Errorf("got \"%s\"; expected \"%s\"", actual, tc.expected)52 }53 if err != tc.err {54 t.Errorf("got \"%s\"; expected \"%s\"", err, tc.err)55 }56 })57 }58}...

Full Screen

Full Screen

direction.go

Source:direction.go Github

copy

Full Screen

...15 return "num_directions"16 }17 return [...]string{"upstream", "downstream"}[d]18}19func ParseDirection(value string) (Direction, error) {20 switch strings.ToLower(value) {21 case "downstream":22 return Downstream, nil23 case "upstream":24 return Upstream, nil25 }26 return NumDirections, ErrInvalidDirectionParameter27}...

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := sarama.NewConfig()4 client, err := sarama.NewClient([]string{"localhost:9092"}, config)5 if err != nil {6 panic(err)7 }8 defer client.Close()9 stream := sarama.NewOffsetManagerFromClient("test", client)10 defer stream.Close()11 offset, err := stream.ParseDirection("test", 0, "latest")12 if err != nil {13 panic(err)14 }15 fmt.Println(offset)16}17import (18func main() {19 config := sarama.NewConfig()20 client, err := sarama.NewClient([]string{"localhost:9092"}, config)21 if err != nil {22 panic(err)23 }24 defer client.Close()25 stream := sarama.NewOffsetManagerFromClient("test", client)26 defer stream.Close()27 offset, err := stream.ParseDirection("test", 0, "earliest")28 if err != nil {29 panic(err)30 }31 fmt.Println(offset)32}33import (34func main() {35 config := sarama.NewConfig()36 client, err := sarama.NewClient([]string{"localhost:9092"}, config)37 if err != nil {38 panic(err)39 }40 defer client.Close()41 stream := sarama.NewOffsetManagerFromClient("test", client)42 defer stream.Close()43 offset, err := stream.ParseDirection("test", 0, "uncommitted")44 if err != nil {45 panic(err)46 }47 fmt.Println(offset)48}

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 svc := dynamodb.New(&aws.Config{Region: "us-west-2"})4 params := &dynamodb.ScanInput{5 TableName: aws.String("TableName"),6 }7 resp, err := svc.Scan(params)8 if err != nil {9 fmt.Println(err.Error())10 }11 fmt.Println(resp)12}13{14 Items: [{15 Name: {16 }17 }],18}

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := sarama.NewConfig()4 consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, config)5 if err != nil {6 fmt.Println("Error creating consumer:", err)7 }8 partitionConsumer, err := consumer.ConsumePartition("my_topic", 0, sarama.OffsetOldest)9 if err != nil {10 fmt.Println("Error creating partition consumer:", err)11 }12 firstOffset, err := partitionConsumer.ParseOffset("oldest")13 if err != nil {14 fmt.Println("Error getting first offset:", err)15 }16 lastOffset, err := partitionConsumer.ParseOffset("newest")17 if err != nil {18 fmt.Println("Error getting last offset:", err)19 }20 fmt.Println("First offset is", firstOffset)21 fmt.Println("Last offset is", lastOffset)22}

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client, err := sarama.NewClient("test", []string{"localhost:9092"}, nil)4 if err != nil {5 panic(err)6 }7 stream, err := client.ConsumePartition("test", 0, sarama.OffsetOldest)8 if err != nil {9 panic(err)10 }11 msg := sarama.StringEncoder("message")12 msg1, err := stream.Next()13 if err != nil {14 panic(err)15 }16 msg2, err := stream.ParseDirection(msg1, msg)17 if err != nil {18 panic(err)19 }20 fmt.Println(msg2)21}

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 stream, err := reddit.NewStream("sample_bot", "sample_bot")4 if err != nil {5 log.Fatal(err)6 }7 defer stream.Stop()8 for {9 select {10 case comment := <-stream.Comments():11 dir, err := comment.ParseDirection()12 if err != nil {13 log.Println(err)14 }15 log.Printf("Direction: %s", dir)16 }17 }18}

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 s.ParseDirection()4}5./1.go:12: s.ParseDirection undefined (type io.ReadWriteCloser has no field or method ParseDirection)6./1.go:12: s.ParseDirection undefined (type io.ReadWriteCloser has no field or method ParseDirection)

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 str = strings.ToLower(str)4 fmt.Println(str)5}6Golang strings.ToUpper() Method7strings.ToUpper(str string) string8import (9func main() {10 str = strings.ToUpper(str)11 fmt.Println(str)12}13Golang strings.ToTitle() Method14strings.ToTitle(str string) string15import (16func main() {17 str = strings.ToTitle(str)18 fmt.Println(str)19}20Golang strings.Index() Method21strings.Index(str, substr string) int22import (23func main() {24 fmt.Println(strings.Index(str, "a"))25}

Full Screen

Full Screen

ParseDirection

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Println("Enter the direction string")3 fmt.Scanln(&direction)4 fmt.Println("The direction type is", stream.ParseDirection(direction))5}6func main() {7 fmt.Println("Enter the direction string")8 fmt.Scanln(&direction)9 fmt.Println("The direction type is", stream.ParseDirection(direction))10}11func main() {12 fmt.Println("Enter the direction string")13 fmt.Scanln(&direction)14 fmt.Println("The direction type is", stream.ParseDirection(direction))15}16func main() {17 fmt.Println("Enter the direction string")18 fmt.Scanln(&direction)19 fmt.Println("The direction type is", stream.ParseDirection(direction))20}21func main() {22 fmt.Println("Enter the direction string")23 fmt.Scanln(&direction)24 fmt.Println("The direction type is", stream.ParseDirection(direction))25}26func main() {27 fmt.Println("Enter the direction string")28 fmt.Scanln(&direction)29 fmt.Println("The direction type is", stream.ParseDirection(direction))30}31func main() {32 fmt.Println("Enter the direction string")33 fmt.Scanln(&direction)34 fmt.Println("The direction type is", stream.ParseDirection(direction))35}

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