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

學無先后,達者為師

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

Go語言單控制器和多控制器使用詳解_Golang

作者:書香水墨 ? 更新時間: 2022-09-18 編程語言

本文實例為大家分享了Go語言單控制器和多控制器使用的具體代碼,供大家參考,具體內容如下

一. 單控制器

  • 在Golang的net/http包下有ServeMux實現(xiàn)了Front設計模式的Front窗口,ServeMux負責接收請求并把請求分發(fā)給處理器(Handler)
  • http.ServeMux實現(xiàn)了Handler接口
type Handler interface {
?? ?ServeHTTP(ResponseWriter, *Request)
}
type ServeMux struct {
?? ?mu ? ?sync.RWMutex
?? ?m ? ? map[string]muxEntry
?? ?hosts bool // whether any patterns contain hostnames
}
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
?? ?if r.RequestURI == "*" {
?? ??? ?if r.ProtoAtLeast(1, 1) {
?? ??? ??? ?w.Header().Set("Connection", "close")
?? ??? ?}
?? ??? ?w.WriteHeader(StatusBadRequest)
?? ??? ?return
?? ?}
?? ?h, _ := mux.Handler(r)
?? ?h.ServeHTTP(w, r)
}

自定義結構體,實現(xiàn)Handler接口后,這個結構體就屬于一個處理器,可以處理全部請求

  • 無論在瀏覽器中輸入的資源地址是什么,都可以訪問ServeHTTP
package main

import "fmt"
import "net/http"

type MyHandler struct {
}

func (mh *MyHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
? ?fmt.Fprintln(res,"輸出內容")
}

func main() {
? ?myhandler := MyHandler{}
? ?server := http.Server{
? ? ? Addr: ? ?"127.0.0.1:8090",
? ? ? Handler: &myhandler,
? ?}
? ?server.ListenAndServe()
}

二.多控制器

在實際開發(fā)中大部分情況是不應該只有一個控制器的,不同的請求應該交給不同的處理單元.在Golang中支持兩種多處理方式

  • 多個處理器(Handler)
  • 多個處理函數(shù)(HandleFunc)

使用多處理器

  • 使用http.Handle把不同的URL綁定到不同的處理器
  • 在瀏覽器中輸入http://localhost:8090/myhandler或http://localhost:8090/myother可以訪問兩個處理器方法.但是其他URl會出現(xiàn)404(資源未找到)頁面
package main

import "fmt"
import "net/http"

type MyHandler struct{}
type MyOtherHandler struct{}

func (mh *MyHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
? ?fmt.Fprintln(res, "第一個")
}
func (mh *MyOtherHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
? ?fmt.Fprintln(res, "第二個")
}

func main() {
? ?myhandler := MyHandler{}
? ?myother := MyOtherHandler{}
? ?server := http.Server{
? ? ? Addr: "localhost:8090",
? ?}
? ?http.Handle("/myhandler", &myhandler)
? ?http.Handle("/myother", &myother)
? ?server.ListenAndServe()
}

多函數(shù)方式要比多處理器方式簡便.直接把資源路徑與函數(shù)綁定

package main

import "fmt"
import "net/http"

//不需要定義結構體
//函數(shù)的參數(shù)需要按照ServeHTTP函數(shù)參數(shù)列表進行定義
func first(res http.ResponseWriter, req *http.Request) {
? ?fmt.Fprintln(res, "第一個")
}
func second(res http.ResponseWriter, req *http.Request) {
? ?fmt.Fprintln(res, "第二個")
}

func main() {
? ?server := http.Server{
? ? ? Addr: "localhost:8090",
? ?}
? ?//注意此處使用HandleFunc函數(shù)
? ?http.HandleFunc("/first", first)
? ?http.HandleFunc("/second", second)
? ?server.ListenAndServe()
}

原文鏈接:https://blog.csdn.net/qq_27870421/article/details/118494202

欄目分類
最近更新