Go搭建一個Web服務器

咱們能夠使用http包創建Web服務器web

 

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "log"
 6     "strings"
 7     "net/http"
 8 )
 9 
10 func sayHelloName(w http.ResponseWriter,r *http.Request){
11     r.ParseForm() // 解析參數
12     fmt.Println(r.Form)
13     fmt.Println("path",r.URL.Path)
14     fmt.Println("scheme",r.URL.Scheme)
15     fmt.Println(r.Form["url_long"])
16     for k,v := range r.Form{
17         fmt.Println("key",k)
18         fmt.Println("val",strings.Join(v,""))
19     }
20     fmt.Fprintf(w,"Hello astaxie!")
21 }
22 
23 func main(){
24     http.HandleFunc("/",sayHelloName) // 設置訪問的路由
25     err := http.ListenAndServe(":9090",nil) // 設置監聽的端口
26     if err != nil{
27         log.Fatal("ListenAndServer Failed:",err)
28     }
29 }

 

上面這個代碼,咱們build以後,而後執行web.exe,這個時候其實已經在9090端口監聽http連接請求了。瀏覽器

在瀏覽器輸入http://localhost:9090服務器

能夠看到瀏覽器頁面輸出了Hello astaxie!函數

能夠換一個地址試試:http://localhost:9090/?url_long=111&url_long=222ui

看看瀏覽器輸出的是什麼,服務器輸出的是什麼?url

在服務器端輸出的信息以下:spa

用戶訪問Web以後服務器端打印的信息code

咱們看到上面的代碼,要編寫一個Web服務器很簡單,只要調用http包的兩個函數就能夠了。orm

相關文章
相關標籤/搜索