日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

使用Golang搭建web服務(wù)的實(shí)現(xiàn)步驟_Golang

作者:周伯通的麥田 ? 更新時間: 2022-06-27 編程語言

如何用golang搭建一個web服務(wù)呢?菜鳥官網(wǎng)的go web編程教程已經(jīng)介紹了web服務(wù)器的工作原理,這里就不贅述了。

我們先看個例子:http.go

package main

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

func main() {
    http.HandleFunc("/test", doRequest)      //   設(shè)置訪問路由
    err := http.ListenAndServe(":8000", nil) //設(shè)置監(jiān)聽的端口
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func doRequest(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()       //解析url傳遞的參數(shù),對于POST則解析響應(yīng)包的主體(request body)
    //fmt.Println(r.Form) //這些信息是輸出到服務(wù)器端的打印信息
    //fmt.Println("path", r.URL.Path)
    //fmt.Println("scheme", r.URL.Scheme)
    //for k, v := range r.Form {
    //    fmt.Println("key:", k)
    //    fmt.Println("value:", strings.Join(v, ""))
    //}
    fmt.Fprintf(w, "service start...") //這個寫入到w的是輸出到客戶端的 也可以用下面的 io.WriteString對象

    //注意:如果沒有調(diào)用ParseForm方法,下面無法獲取表單的數(shù)據(jù)
    //query := r.URL.Query()
    var uid string // 初始化定義變量
    if r.Method == "GET" {
        uid = r.FormValue("uid")
    } else if r.Method == "POST" {
        uid = r.PostFormValue("uid")
    }
    io.WriteString(w, "uid = "+uid)
}

go run http.go命令運(yùn)行程序。

之后在瀏覽器中輸入地址:http://127.0.0.1:8000/test?uid=10086,看下結(jié)果。

在main函數(shù)中,我們從net/http包中調(diào)用了一個http.HandleFucn函數(shù)來注冊一個處理函數(shù)

這個函數(shù)接受兩個參數(shù)。第一個是字符串,這個就是進(jìn)行路由匹配,我這里是/test路由。第二個參數(shù)是一個func (ResponseWriter, Request)的簽名。

我們的doRequest函數(shù)就是這樣的簽名。下一行中的http.ListenAndServe(":8000", nil),表示監(jiān)聽localhost的8000端口,暫時忽略掉nil。

在doRequest函數(shù)中我們有兩個參數(shù),一個是http.ResponseWriter類型的。它類似響應(yīng)流,實(shí)際上是一個接口類型。

第二個是http.Request類型,類似于HTTP 請求。我們不必使用所有的參數(shù),如果只是簡單的輸出,那么我們只需要使用http.ResponseWriter,io.WriteString,將會把輸出流寫入數(shù)據(jù)。

我們再稍微改下,大家請注意修改的部分(這里我們只調(diào)整 main函數(shù)部分代碼)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/test", doRequest)
    err :=  http.ListenAndServe(":8000", mux) //設(shè)置監(jiān)聽的端口
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

這個例子中,我們不再在函數(shù)http.ListenAndServe使用nil了。這個例子跟上面的例子其實(shí)是一樣的。使用http注冊hanlder 函數(shù)模式就是用的ServeMux。
我們再調(diào)整下看下更復(fù)雜的例子:

package main

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

var mux map[string]func(http.ResponseWriter, *http.Request)

func main() {
    server := http.Server{
        Addr:    ":8000",
        Handler: &doHandler{},
    }

    mux = make(map[string]func(http.ResponseWriter, *http.Request))
    mux["/test"] = doRequest

    err := server.ListenAndServe()
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

type doHandler struct{}

func (*doHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if res, ok := mux[r.URL.String()]; ok {
        res(w, r)
        return
    }

    io.WriteString(w, "url params: "+r.URL.String())
}
func doRequest(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()                      //解析url傳遞的參數(shù),對于POST則解析響應(yīng)包的主體(request body)
    fmt.Fprintf(w, "service start...") //這個寫入到w的是輸出到客戶端的 也可以用下面的 io.WriteString對象
}

這個例子我們沒有定義ServeMux,而是使用了http.Server。都是用net/http包運(yùn)行了服務(wù)器。

原文鏈接:https://www.cnblogs.com/phpper/p/10408206.html

欄目分類
最近更新