Saturday, June 11, 2011

Web Programming with Go - first web Hello world

If you’ve already gone through some of the earlier tutorials in this series, you should be quite comfortable getting onto programming the web with Go. Let’s jump right to it and then we shall analyze the code. There is a chance that there might be people arriving here for the first time, so we shall also take some time to go over the basic concepts of both the Go programming language and about web programming.

Web services wait on the computer for users to connect and request information and processing. The way to reach the computer and the service is via a URL - a unique address on the web that identifies what needs to be done. For example, the sample URL
would indicate that there is probably a service called deposit waiting to serve on a machine called at the port 80 and can be accessed via the protocol http. We could additionally give parameters and variables so that the service can work on the data.

Let’s do a basic Go web program and then analyze the code. In this program, we shall start a simple service on the local machine. We will have the program running on port 9999. When you access the local machine at http://localhost:9999 (which is the same as, it will print a text message on the screen.

Full program: webhello.go
package main

import (
    "net/http" //package for http based web programs

func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Println("Inside handler")
    fmt.Fprintf(w, "Hello world from my Go program!")

func main() {
    http.HandleFunc("/", handler) // redirect all urls to the handler function
    http.ListenAndServe("localhost:9999", nil) // listen for connections at port 9999 on the local machine

Compiling the code: You can use a Makefile. You can read more about make files in Go at Compiling and Linking with Makefiles. The Makefile that I used is given below. You will have to set the environment variable GO_HOME to the directory where Go is installed.

Full code: Makefile
include ${GO_HOME}/go/src/


include ${GO_HOME}/go/src/Make.cmd

    ${GOFMT} -w ${SRC}

Assuming you have got all of this setup, follow the steps below.
* At the command prompt compile and link the code you wrote by entering the command:
* This should have produced an executable. Run this by typing at the command prompt:

* Run the program with go run webhello.go
* Your web service is now running and waiting for connections.
* Go to http://localhost:9999 on your browser.
* You should see a page with this output: Hello world from my Go program!.

Hopefully all that has gone well for you. First you can bask a little in the personal glory of having written your first working Go program for the web. … Done? Ok, now let’s analyze what we’ve done in the code. If you have already done some web programming, you would have already figured out most of the code and flow, but if you haven’t, here are the details.

* like all Go programs that need to be executed, our program has a package main.
* to work with some printing functions, it imports the package fmt
* for web related http functionality, we import the package http. Any functions within that we refer as http.function_name
* within the main program, we redirect any incoming requests to the handler function. We do this by calling http.HandleFunc and passing it two parameters - the first one is a part of the incoming url, and the second is the method capable of handling it.
* we then make the program listen on the local machine’s port 9999 for users to connect by using http.ListenAndServe("localhost:9999", nil)
* when a user connects, the programs responds with a text that is sent back to the browser.
* all the parameters of a request can be received via the parameter http.Request in the handler. You can get the URL, the input values and other details.
* you send content back to the browser using the received pointer parameter http.ResponseWriter
* the code http.HandleFunc("/", handler) meant that all requests that had the url starting with what we gave in http.ListenAndServe, will be redirected to our handler function.

Let’s now expand that sample a little where we can ask different things of the web browser with different URLs. In the next version of the same program, we will have two handlers: one two print strings as it is given and another to capitalize it.

Full program
package main

import (

func helloHandler(w http.ResponseWriter, r *http.Request) {
    remPartOfURL := r.URL.Path[len("/hello/"):] //get everything after the /hello/ part of the URL
    fmt.Fprintf(w, "Hello %s!", remPartOfURL)

func shouthelloHandler(w http.ResponseWriter, r *http.Request) {
    remPartOfURL := r.URL.Path[len("/shouthello/"):] //get everything after the /shouthello/ part of the URL
    fmt.Fprintf(w, "Hello %s!", strings.ToUpper(remPartOfURL))

func main() {
    http.HandleFunc("/hello/", helloHandler)
    http.HandleFunc("/shouthello/", shouthelloHandler)
    http.ListenAndServe("localhost:9999", nil)

After you make and execute the program, go to the following links.

Hello Mary!

Hello MARY!


  1. Speaking as a neophyte coder who has been following along, this is the part in your tutorial where I shit my pants.

  2. I have no words for this great post such a awe-some information i got gathered. Thanks to Author.
    Android app developer| Android apps development|

  3. Nice Tutorial, but as it is for beginners you could mention that no one should have running something like this in an productive environment as it opens a big door for XSS-attacks. Actually if this runs under you compromise the whole * .

  4. In go1, the 'import "http"' should be 'import "net/http"' instead.

    1. Thanks Zhe. Even if late, I've updated the code and tutorial now.

  5. What do you mean "we then make the program listen on the local
    machine’s port 9999"? Is there a way to make our program listen on
    some other machine's ports? Or do you mean "we then make the program
    listen to port 9999 on the localhost interface"?

    1. Only the machine you are running the program.

  6. Hi,The site is very well designed, has a nice colors scheme in Web Design Cochin and it can be an example for how to design with end purpose in mind.Thanks.......

  7. Web design Jaipur:-
    All websites need to be maintained in order to keep website content current. It includes revising, editing or other changes existing web pages to keep your website update.

  8. Great post , How to pass parameters from URL to helloHandler method..etc

  9. Great post , Actually if this runs under you compromise the whole * .

  10. Thanks for sharing the information. It is very useful for my future. keep sharing
    i like play games friv 4 online and play games2girls 2 online free and play game friv games and games 2 girls ! have fun!

  11. Great html tutorials tips for programming. It can help better for website developers.Thanks for this useful post.

  12. Technology have increased to the core, that before buying a product consumers are not at all hesitating to know about the product and the dealer. So it is the duty of every business owner to deliver an attractive website to their consumers. Thanks for sharing this information anyway. Keep blogging.

    web designing course in chennai | wweb design course | JAVA Training in Chennai

  13. An impressive and informative information, thanks for shared and enjoyed to reading this post.

  14. In my opinion, great content is above all. So focusing on creating good quality of content is the solution.

  15. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from Pprogramming

  16. Thanks for sharing this informative content which provided me the required information about the latest technology.
    Ethical Hacking Course in Chennai | Ethical Hacking Training in Chennai

  17. Thanks for sharing information to our knowledge, it helps me plenty keep sharing…
    Java Training in Chennai | JAVA Course in Chennai

  18. Our Complete in depth Java training course takes you to TOP Level IT companies with high end package. Arcus Offers Java J2EE real time training with placement assurance..
    java training in chennai

  19. Thanks for sharing this good stuff! Keep up the great work, we look forward to reading more from you in the future!
    Friv 100

  20. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write
    Facebook Lite

  21. Thank you for sharing valuable information. Nice post. I enjoyed reading this post.Can you play more games at :
    ninjago game | strikeforce kitty 2 | red ball | ninjago games | strike force kitty

  22. You want to relax after a stressful working hours. Refer to our website. Hope you get the most comfort.
    Thanks for sharing !
    Kizi 100
    gold Miner 2
    unfair Mario 2
    cubefield 2
    tanki Online 2

    Friv Games
    Friv 200

  23. This is the great piece of content I haven't seen before thanks very much for sharing this in here.
    Best web design company in chennai

  24. Very helpful advice in this particular post! It’s the little changes that make the largest changes. Thanks for sharing!
    minecraft | baixar facebook | baixar whatsapp | facebook baixar | baixar photo grid

  25. Great Work. This post is worth everyone’s attention. web design company in chennai

  26. This is my first visit to your blog, your post made productive reading, thank you. dot net training in chennai

  27. Informative article, just what I was looking for.seo services chennai

  28. Do you want to design a good looking website in Lebanon and want to get apps and social media network? We are here to do these and we are professional in web development Lebanon and app development Lebanon or also for social media in Lebanon. We are giving best quality and cheap prices.

  29. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.
    PHP Training in Chennai

  30. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Matlab Training in chennai

  31. Informative article, just what I was looking for.seo services chennai

  32. Can truly relate and retain this outstanding post. Very well written. web design company Chennai

  33. Thank your share! I’m very happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that is at the other blogs. Appreciate your sharing this greatest doc!

  34. Thanks for your post! Through your pen I found the problem up interesting! I believe there are many other people who are interested in them just like me! Thanks your shared!... I hope you will continue to have similar posts to share with everyone!
    slither io

  35. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

  36. There are things I can not understand but I will learn it. I think nothing is too late. Then I realized that I had improved a lot.

  37. HI , interested to read this program easy way to understand for beginners"web designing courses

  38. SEO Experts Lounge. SEO company in pakistan. web development in Pakistan. web designing in Pakistan. best seo company in Lahore. best seo company in Pakistan.
    SEO Experts Lounge
    Web Development Company in Pakistan
    Web Designing Company Pakistan
    SEO Company in Lahore
    PPC Service in Pakistan

  39. Really good Blog i appreciate your hard work and research. Very helpful information. Marketing92 is the IT Company in Lahore, Pakistan. The Service of Facebook Marketing in Lahore and SEO Services in Lahore, Pakistan, will increase the numbers of customers on Your Business and increase the traffic of your website.

  40. Nice post. Thanks for sharing such an informative post. This is really useful.
    Android Training in Lucknow | Best Android Training in Lucknow

  41. It seems I'm on the right track, I hope I can do well. The result was something I did and was doing to implement it.

  42. There are so many useful information in your post, I like it all the time. And I want to share this boost app ranking with you, you can take a look. This is very useful.


If you think others also will find these tutorials useful, kindly "+1" it above and mention the link in your own blogs, responses, and entries on the net so that others also may reach here. Thank you.