go 語言實現 web 服務器很容易。這樣就可以很任意的建立 web 應用而互不干擾。當然,端口和IP要規劃好。不過這里不討論這個范疇的內容。我們只實現最基本的通過瀏覽器能夠打印出我們想要的文字就可以了。
我們需要實現 http.Handler 。
func sayhello_cofox(w http.ResponseWriter, r *http.Request)
然后用 http.HandleFunc 設置訪問的路由
使用 http.ListenAndServe 設置主域名和端口號
err := http.ListenAndServe(":4000", nil)
這個例子中,我們使用 4000 端口。主域名省略。這樣所有本機 IP 和域名就都可以使用。
比如:
http://192.168.1.105:4000/
http://127.0.0.1:4000/
http://localhost:4000/
完整代碼
package main
import(
"net/http"
"fmt"
"log"
"time"
"strings"
)
func sayhello_cofox(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析參數,默認是不會解析的
fmt.Println(r.Form)
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 Cofox!" + time.Now().String())
}
func main() {
http.HandleFunc("/", sayhello_cofox) //設置訪問的路由
err := http.ListenAndServe(":4000", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
本例子編譯后運行。然后打開瀏覽器,輸入本地相應地址訪問。
我實驗的機器是這三個本地地址都可以訪問
http://192.168.1.105:4000/
http://127.0.0.1:4000/
http://localhost:4000/
瀏覽器運行結果
Hello Cofox!2017-08-20 19:03:52.0956481 +0800 CST