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