Golang 探究http

分别用三种方式实现 http 服务器。

Golang 自制Http中间件

server 1

package main

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

func sayHello(w http.ResponseWriter, r *http.Request)  {
    io.WriteString(w, "Hello world, this is version 1")
}

func main()  {
    // 访问: http://localhost:8888/

    // 设置路由
    http.HandleFunc("/", sayHello)

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

server 2

package main

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

type myHandler struct {
}

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "URL: " + r.URL.String())
}

func sayHello(w http.ResponseWriter, r *http.Request)  {
    io.WriteString(w, "Hello world, this is version 2")
}

func main()  {
    // 访问:http://localhost:8888/
    // 访问:http://localhost:8888/testing?mod=index&action=index
    // 访问:http://localhost:8888/hello

    mux := http.NewServeMux()
    mux.Handle("/", &myHandler{})
    mux.HandleFunc("/hello", sayHello)

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

server 3

package main

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

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

type myHandler struct {
}

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // 如果在 map 中定义了路由就执行对应的函数
    if h, ok := mux[r.URL.String()]; ok {
        h(w, r)
        return
    }
    // 否则打印出 URL
    io.WriteString(w, "URL: " + r.URL.String())
}

func sayHello(w http.ResponseWriter, r *http.Request)  {
    io.WriteString(w, "Hello world, this is version 3")
}

func sayBye(w http.ResponseWriter, r *http.Request)  {
    io.WriteString(w, "Bye bye, this is version 3")
}

func main()  {
    // 访问:http://localhost:8888/
    // 访问:http://localhost:8888/bye
    server := http.Server{
        Addr:              ":8888",
        Handler:           &myHandler{},
        ReadTimeout:       5 * time.Second,
    }

    mux = make(map[string]func(http.ResponseWriter, *http.Request))
    mux["/"] = sayHello
    mux["/bye"] = sayBye

    err := server.ListenAndServe()
    if err != nil {
        log.Fatal(err)
    }
}
讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!