Building a simple web server with Go.

(Notes from Microservices With Go by Nic Richardson)

Building a web server in Go is pretty straightforward, using the HTTP package. We’ll be using net/http package.

Example: basic_server.go

package main

import (
    "fmt"
    "log"
    "net/http"
) 
func main() { 
    port := 8080 

    http.HandleFunc("/helloworld", helloWorldHandler) 
 
    log.Printf("Server starting on port %v\n", 8080) 
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil)) 
 } 
 
 func helloWorldHandler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprint(w, "Hello World\n") 
 }

HandleFunc() on the http package creates a handler, mapping the path in the first parameter to the function in the second parameter.

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)

ListenAndServe() starts an HTTP server with a given address and handler. Here, we are binding it to port 8080. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux.

If the ListenAndServe function fails to start a server it will return an error, the most common reason for this is that you may be trying to bind to a port that is already in use on the server. In our example, we are passing the output of ListenAndServe straight to log.Fatal(error), which is a convenience function equivalent to calling fmt.Print(a ...interface{}) followed by a call to os.Exit(1). Since ListenAndServe blocks if the server starts correctly we will never exit on a successful start.

$ go run ./basic_server.go  

You should now see the application output:

 Server starting on port 8080  

If you see something like the following, it means you are already running an application on port 8080

 listen tcp :8080: bind: address already in use exit status 1  

You can check the list of running programs using this command

$ ps -aux | grep 'go run'  

If there is another program running, you can kill it. If that is not possible, choose a different port for your program.

Once the server is up and running, type in the URI  http://127.0.0.1:8080/helloworld or http://localhost:8080/helloworld and if things are working correctly you should see the following response from the server:

Hello World 

If you see the above response, that means you have your a basic http server in Go up and running.

How to convert a list to string for display in Python.

(Copied from: https://www.decalage.info/en/python/print_list)

There are a few useful tips to convert a Python list (or any other iterable such as a tuple) to a string for display.

pre { background-color:#F0F0F0; }

First, if it is a list of strings, you may simply use join this way:

>>> mylist = ['spam', 'ham', 'eggs']
>>> print ', '.join(mylist)
spam, ham, eggs

Using the same method, you might also do this:

>>> print '\n'.join(mylist)
spam
ham
eggs

However, this simple method does not work if the list contains non-string objects, such as integers.

If you just want to obtain a comma-separated string, you may use this shortcut:

>>> list_of_ints = [80, 443, 8080, 8081]
>>> print str(list_of_ints).strip('[]')
80, 443, 8080, 8081

Or this one, if your objects contain square brackets:

>>> print str(list_of_ints)[1:-1]
80, 443, 8080, 8081

Finally, you may use map() to convert each item in the list to a string, and then join them:

>>> print ', '.join(map(str, list_of_ints))
80, 443, 8080, 8081
>>> print '\n'.join(map(str, list_of_ints))
80
443
8080
8081
 
 

How to remove stuck entries from Control Panel

Sometimes, even after you uninstall a software, its entry is still available in the Programs and Features section of Control Panel. When you attempt to uninstall it again or remove it from this list, the software complains it cannot be uninstalled or has encountered an error during the uninstall. Such entries can be removed by editing the Registry. Now since this method involves editing/deleting Registry values, please be careful and always create a registry backup before proceeding. Below are the steps:

  1. Click on Start and type ‘regedit’ to open the registry.
  2. Navigate to the following key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

Check for the key ‘Display Name’ on the right side to identify the correct software that you want to remove. If you don’t find your software listed in this location, try looking here:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

3. Once you find the program you want to delete, right-click on the registry key on the left hand side and click on Delete.

Once deleted from registry, the entry from Programs and Features in Control Panel will be removed.

 

 

Adding Git Auto-completion.

Git Auto-completion is quite useful to auto-complete git commands on the terminal. Here is how to enable this nice script.

1) Using curl, download the script to your home directory:

curl -OL https://github.com/git/git/raw/master/contrib/completion/git-completion.bash

2) Make it a dot file:

mv ~/git-completion.bash .git-completion.bash

3) Add this little code snippet to your ~/.bash_profile file:


if [ -f ~/.git-completion.bash ]; then
    source ~/.git-completion.bash
fi

This basically checks if .git-completion.bash exists or not, and if it does, it loads it.4) Quit the terminal window and open it again for the changes to take effect. Alternatively, run

source ~/.bash_profile.

5) To see if this worked correctly, type ‘git h’ and hit tab. It should expand it to ‘git help’.

Reference: Lynda.com Git Tutorials.

Difference between === and == in Javascript.

JavaScript has both strict and type–converting comparisons. A strict comparison (e.g., ===) is only true if the operands are of the same type. The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison.
This means that, the == operator will compare for equality after doing any necessary type conversions. The ===operator will not do the conversion, so if two values are not the same type === will simply return false. From performance point of view, It’s this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.
Example:

1 == 1    // true
1 == “1”  //true
1 == ‘1’  //true
1 === 1   //true
1 === “1” //false
For relational abstract comparisons (e.g., <=), the operands are first converted to primitives, then to the same type, before comparison.Strings are compared based on standard lexicographical ordering, using Unicode values. 

Features of comparisons:
  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value).NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two distinct objects are never equal for either strict or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.
  • Null and Undefined Types are strictly equal to themselves and abstractly equal to each other.

References: Stack Overflow
Comparison Operators

 

The Beginning

As my first blog post, I thought I should take some time (and space!) to elaborate on what I am attempting here. Since I have decided to go with a technical theme for this blog, I thought of going back to the basics and the first steps. And thats what brought me to start a section dedicated to interview questions. In my experience, practicing interview questions has been a great way to consolidate the basics and learning some “cool tricks”. They are a fun way to challenge oneself. Well they don’t seem that much fun when faced with in an interview 😛 But anyway, there is a point in every software developer’s life when they have to go through the “painful” process of interview preparation. This is one small attempt to ease the process to some extent. 
 
There are several books, blogs and websites available which help you prepare for a technical interview. I have read and followed a few of them and they have some really great advice and good set of problems. To name a few:
 
Books:
 
Websites:
 
Now time for some advice! The major lessons that I have learnt while preparing for technical interviews are:
 
1) Learn to think: This should essentially be done when in undergrad/grad school, but its never too late. While practicing the interview questions, never jump to see the solution. No matter how frustrating it gets or how much ever you are pressed for time, do not see the solution unless you have given your honest effort in solving the problem. Practicing as many problems as you can helps but there is a very important thing to understand here – practice does NOT mean “memorize”! Never attempt to memorize the solution to a problem. That won’t help much. Always try to think through it. So practicing a large number of problems alone without actually thinking, is not the key to crack the interviews. Practicing how to think through a problem is. Developing skills and an understanding to break down a problem and attempting to solve it is more essential and beneficial than to memorize handful of “tricks”. 
 
2) Revisit the undergrad classes: If you sighed with relief thinking that once you are done with your Algorithms and Data Structures undergrad classes, you won’t have to face them again, then it gives me an evil pleasure to tell you that you are wrong 🙂 Algorithms and Data Structures will come and haunt you more often than you would think! So better be friends with them to avoid scary surprises. Other than Algorithms and Data Structures, there are many more fundamental courses that you should be comfortable with. Here is a really helpful blog post by Steve Yegge on what knowledge and skills are expected of a candidate. This post talks in terms of phone interviews, but the topics listed are pretty much what any Computer Science grad should be aware of. 
 
3) Practice on paper or white board: And don’t even begin with an IDE! Writing code on paper/whiteboard is altogether a different ballgame than coding with a compiler or IDE. You tend to make lot more mistakes on paper and miss out on those corner cases. Once you have designed and coded your function, run some test cases by hand. You can catch some bugs during this process. Type in your solution into the IDE only when you think its the final solution. Once you run your function, make note of the errors that you made. Then learn from the mistakes. Always think about the test cases that can fail your function. Think in terms of time and space complexity, attempt to find some more bugs and try to improve the efficiency of the code. 
 
4) Start Simple: After you read the problem statement, think in terms of how a human would solve it. For example, to sort an array of numbers, how would you do it by hand? Forget about the myriad types of sorting algorithms you would have studied. Start simple. Develop an algorithm for how you would sort. Once you have polished the pseudo-code, now think in terms of time and space complexity for your solution. Think about all the various ways you can improve it. Would using a different data structure help? Jumping into finding an efficient solution before devising a working one often leads to many changes being made to the solution and fogs the clarity in thinking.
 
5) Be confident: Cliche but essential. So you couldn’t think through a problem that seemed somewhat simple. And it was really simple when you finally gave up and browsed through the solution. And this is happening after you had invested a good amount of time in practice. Don’t worry! These are the times when you need to feel confident and remain focussed without getting frustrated. Its hard but its necessary. Revise the topic that you fumbled in. Practice couple more similar problems and make sure this time you get it. Then without letting this shake your confidence, move on.
 
These were the important lessons that I learnt while preparing for interviews. I hope this guidance helps.