2.3 KiB
3.2 Build a simple web server
We talked about that web applications are based on HTTP protocol, and Go provides fully ability for HTTP in package net/http, it's very easy to setup a web server by 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 executed above code, it starts 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 arguments: http://localhost:9090/?url_long=111&url_long=222
Now see what happened in both client and server sides.
You should see following information in your server side:
Figure 3.8 Server printed information
As you can see, we only need to call two functions to build a simple web server.
If you are working with PHP, you probably want to ask do we need something like Nginx or Apache, the answer is we don't need because Go listens to TCP port by itself, and the function sayhelloName is the logic function like 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 use two simple functions to setup a simple web server in this section, and this simple server has already had ability for high concurrency. We will talk about how to use this feature in next two sections.
Links
- Directory
- Previous section: Web working principles
- Next section: How Go works with web
