3.2 Build a simple web server

We’ve discussed that web applications are based on the HTTP protocol, and Go provides full HTTP support in the net/http package. It’s very easy to set a web server up using this package.

Use http package setup a web server

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "log"
  7. )
  8. func sayhelloName(w http.ResponseWriter, r *http.Request) {
  9. r.ParseForm() // parse arguments, you have to call this by yourself
  10. fmt.Println(r.Form) // print form information in server side
  11. fmt.Println("path", r.URL.Path)
  12. fmt.Println("scheme", r.URL.Scheme)
  13. fmt.Println(r.Form["url_long"])
  14. for k, v := range r.Form {
  15. fmt.Println("key:", k)
  16. fmt.Println("val:", strings.Join(v, ""))
  17. }
  18. fmt.Fprintf(w, "Hello astaxie!") // send data to client side
  19. }
  20. func main() {
  21. http.HandleFunc("/", sayhelloName) // set router
  22. err := http.ListenAndServe(":9090", nil) // set listen port
  23. if err != nil {
  24. log.Fatal("ListenAndServe: ", err)
  25. }
  26. }

After we execute the above code, the server begins listening to port 9090 in local host.

Open your browser and visit http://localhost:9090. You can see that Hello astaxie is on your screen.

Let’s try another address with additional arguments: http://localhost:9090/?url_long=111&url_long=222

Now let’s see what happens on both the client and server sides.

You should see the following information on the server side:

3.2. Build a simple web server - 图1

Figure 3.8 Server printed information

As you can see, we only need to call two functions in order to build a simple web server.

If you are working with PHP, you’re probably asking whether or not we need something like Nginx or Apache. The answer is we don’t, since Go listens to the TCP port by itself, and the function sayhelloName is the logic function just like a controller in PHP.

If you are working with Python you should know tornado, and the above example is very similar to that.

If you are working with Ruby, you may notice it is like script/server in ROR (Ruby on Rails).

We used two simple functions to setup a simple web server in this section, and this simple server already has the capacity for high concurrency operations. We will talk about how to utilize this in the next two sections.