提示:本系列文章適合對Go有持續衝動的讀者

初探golang web服務

golang web開發是其一項重要且有競爭力的應用,本小結來看看再golang中怎麼建立一個簡單的web服務。

在不適用web框架的情況下,可以使用net/http包搭建一個web服務。

  1. 這裡我們使用net/http建立一個列印請求URL的web服務。
package main

import (
//"log"
"fmt"
"net/http"
) func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:6677", nil) }
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "url.path=%q\n", r.URL.Path) //輸出到檔案流
}

http.HandleFunc函式可以理解為URL路由。

http.ListenAndServe是web服務的建立核心。

handler是http請求處理函式,接受一個http.ResponseWriter檔案流 和http.Request型別的物件。

[root@VM-0-5-centos ~]# curl localhost:6677/123
url.path="/123"

  1. 我們通過handler函式來對訪問url做訪問數計算。

引入golang sync中的互斥鎖,這樣同時存在多個請求時只有一個goroutine改變count計數。互斥鎖後續深入瞭解。

package main

import (
//"log"
"fmt"
"net/http"
"sync"
) var count int
var mutex sync.Mutex //使用互斥鎖
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:6677", nil) }
func handler(w http.ResponseWriter, r *http.Request) {
mutex.Lock()
count++
mutex.Unlock()
fmt.Fprintf(w, "request url.path:%q has %d times\n", r.URL.Path, count)
}

我們來看看請求結果如下:

[root@VM-0-5-centos ~]# curl localhost:6677/golang
request url.path:"/golang" has 1 times
[root@VM-0-5-centos ~]# curl localhost:6677/golang
request url.path:"/golang" has 2 times
[root@VM-0-5-centos ~]# curl localhost:6677/golang
request url.path:"/golang" has 3 times

  1. http.Request型別物件除了URL.Path屬性外還有MethodProto等。我們通過handler函式分別打印出來。
package main

import (
//"log"
"fmt"
"net/http"
"sync"
) var count int
var mutex sync.Mutex //使用互斥鎖
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe("localhost:6677", nil) }
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s,%s,%s,\n", r.Method, r.URL, r.Proto)
fmt.Fprintf(w, "host:%q\nremoteaddr:%q\n", r.Host, r.RemoteAddr)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q]:%q\n", k, v)
}
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q]:%q\n", k, v)
} }

建立表單接受後輸出如下:

//output
GET,/helloweb,HTTP/1.1,
host:"localhost:6677"
remoteaddr:"127.0.0.1:58088"
Header["User-Agent"]:["curl/7.29.0"]
Header["Accept"]:["*/*"]
Form[parm1]:hello
Form[parm2]:web

本次簡單的瞭解了一下golang web服務,也是初嘗章節結束。接下來會比較深入的學習golang的精彩細節與精華。


文章有不足的地方歡迎在評論區指出。

歡迎收藏、點贊、提問。關注頂級飲水機管理員,除了管燒熱水,有時還做點別的。