Skip to content

Latest commit

 

History

History
65 lines (45 loc) · 2.4 KB

File metadata and controls

65 lines (45 loc) · 2.4 KB

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

package main

import (
	"fmt"
	"net/http"
	"strings"
	"log"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()  // parse arguments, you have to call this by yourself
	fmt.Println(r.Form)  // print form information in server side
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k, v := range r.Form {
    	fmt.Println("key:", k)
    	fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello astaxie!") // send data to client side
}

func main() {
	http.HandleFunc("/", sayhelloName) // set router
	err := http.ListenAndServe(":9090", nil) // set listen port
	if err != nil {
    	log.Fatal("ListenAndServe: ", err)
	}
}

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:

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 no, 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.

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.

Links