Go语言学习笔记(3)--- http

go 刘宇帅 5年前 阅读量: 997

Hello world

Go 标注库 net/http 中封装了丰富的 http 服务相关的方法,只需要使用标准库就可以方便的构建 http 服务。
Hello world 示例

package main

import (
    "net/http"
    "fmt"
)

type Handler struct {
}

func (h *Handler)ServeHTTP(rep http.ResponseWriter, req *http.Request)  {
    rep.Write([]byte("Hello world"))
}

func main() {
    http.Handle("/", &Handler{})

    http.ListenAndServe(":8081", nil)
}

使用 net/http 包,我们只需要实现一个 Server 接口的 struct 即可,Server 接口只有一个 函数 ServeHTTP(ResponseWriter, Request)
监听
Handler*有两种形式,一种是像上面那样,还有一种如下

func main() {
    http.ListenAndServe(":8081", &Handler{})
}

两种都可以,net/http 包实现基于一个 Server 结构体,第二种方式直接把 Handler 设置为 Server 实例的字段 handler,而第一种使用了 net/http 包提供的默认 Handler 的实现 ServeMux, 如果 Server 实例 handler 为空那么就使用默认的 Handler。ServeMux 是一个实现了多路由的 Handler 接口的 struct,我们可以通过它添加多个路由。

func main() {
    http.Handle("/api", &Handler1{})
    http.Handle("/web", &Handler2{})
    http.ListenAndServe(":8081", nil)
}

http 客户端访问测试代码

package main

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

func main() {
    resp, err := http.Get("http://127.0.0.1:8081")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    responseBody,err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(responseBody))
}

实现一个 Handler 接口还是需要些不少代码的,net/http 提供了另外一个函数 HandlerFunc。

package main

import (
    "net/http"
    "fmt"
)

func main() {
    http.HandleFunc("/", func(rep http.ResponseWriter, req *http.Request) {
        fmt.Println(req.RequestURI)
        rep.Write([]byte("Hello world"))
    })

    http.ListenAndServe(":8081", nil)
}

net/http 实现了一个 type HandlerFunc func(ResponseWriter, Request) 类型,并给该类型添加了func (f HandlerFunc) ServeHTTP(w ResponseWriter, r Request)方法。net/http 把我们传入的函数转化为 HandlerFunc 类型,并把其绑定到 ServeMux 的默认实例上。

默认 Handler

NotFountHandler

http.ListenAndServe(":8081", http.NotFoundHandler())

RedirectHandler

    http.ListenAndServe(":8081", http.RedirectHandler("/test", 302))

FileServer

    http.ListenAndServe(":8081", http.FileServer(http.Dir("./")))

提示

功能待开通!


暂无评论~