Category Archives: development

Golang: HTTP Client & Server with Query Params

Client

func TestDelete(id string, registered bool) {
      path := "http://localhost:8085/v1/shops"

      // Create client
      client := &http.Client{}

      // Create request
      req, err := http.NewRequest("DELETE", path, nil)
      if err != nil {
          fmt.Println(err)
          return
      }

      q := req.URL.Query()
      q.Add("id", r.UID)
      q.Add("registered", strconv.FormatBool(registered))
      req.URL.RawQuery = q.Encode()

      fmt.Println(req.URL.String())

      // Fetch Request
      resp, err := client.Do(req)
      if err != nil {
          fmt.Println(err)
          return
      }
      defer resp.Body.Close()

      // Read Response Body
      respBody, err := ioutil.ReadAll(resp.Body)
      if err != nil {
          fmt.Println(err)
          return
      }
      
      fmt.Printf("response=%v body=%v", resp, respBody)
      
      // the server returns a slice in response body
      var out []string
      json.Unmarshal(respBody, &out)
      fmt.Printf("response=%s", out)
  }

Server

var ( 
    errQP = errors.New("query param error")
)

func handleDelete(r *http.Request) (*response, error) {
	uid := r.URL.Query().Get("id")
	registration := r.URL.Query().Get("registration")
	if uid == "" || legacy == "" {
		glog.Errorf("handleDeletes: Url Param missing uid=%s registration=%s", uid, registration)
		return nil, errQP
	}

	isRegistered, err := strconv.ParseBool(registered)
	if err != nil {
		glog.Errorf("handleDelete: failed to parse id=%s registration=%s", uid, registration)
		return nil, err
	}
	// deletedShops is a slice
	deletedShops, err := deleteShops(id, isRegistered)
	if err != nil {
		glog.Errorf("handleDelete: failed id=%s registration=%v err=%s", id, isRegistered, err)
		return nil, err
	}

	return &response{
		status: 200,
		body:   deletedShops,
	}, nil
}

Points to Note

  • The above code allows a client to encode query params in a request.
  • The Client gets a slice in response.
Advertisements

C++: Max Product in a Matrix witout Backtrack

Problem

Given a matrix, find the path from top left to bottom right with the greatest product by moving only down and right.

The code is in C++.
The only moves allowed are down and right. The solution works for positive numbers.

Reference

Written with StackEdit.

A Resilient Web API Client in Ruby

Ruby HTTP client is not sophisticated enough to handle errors gracefully. I came across a well-designed client for a web service at [AppSignal].
(https://blog.appsignal.com/2018/05/16/ensure-retry-and-reraise-exceptions-in-ruby.html)

The code for the client is as following:

The code has the following logic:

  1. Try to establish a connection with the server.
  2. The request has a timeout and connection refused exceptions.
  3. If retries fail, code raise the last seen exception.
  4. Each retry has increased timeout.

Written with StackEdit.

C++: Find Longest Sequence of Numbers in An Unsorted Array

Given an unsorted array, find the length of the longest sequence of consecutive numbers in the array.

$ g++ -std=c++11 ./FindLongestSequence.cc
$ ./a.out
4

Reference

Written with StackEdit.

C++: Find Duplicates in a Positive Integers Range 1 to N

Given an array of integers where each value 1 <= x <= len(array), write a function that finds all the duplicates in the array.

C++ Solution

$ g++ -std=c++11 ./FindDuplicates.cc
$ ./a.out
1 2

Reference

Python Code To Find Median of Sorted Arrays of Equal Size

The following code has two implementations of finding median of two sorted arrays in O(n) and O(log n).

Reference