Go语言学习之net/http包(The way to go)

生命不止,继续go go go!!!

从包名就能看到了吧,是golang中提供http的包:
provides HTTP client and server implementations.

先看一个例子:

package main

import "net/http"

func main() {
    http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))
}

然后浏览器输入:localhost:8080/main.go

http.FileServer

func FileServer(root FileSystem) Handler

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.
上面的实例代码中,使用是“.”,表示的是当前目录,也可以这样:

http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))

ListenAndServe

func ListenAndServe(addr string, handler Handler) error

HandleFunc
HandleFunc registers the handler function for the given pattern in the DefaultServeMux.

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

创建一个简单的web服务器
那么,看下面的例子,应用ListenAndServe和HandleFunc:

package main

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

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "hello, world!\n")
}

func main() {
    http.HandleFunc("/hello", HelloServer)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

浏览器输入:
http://localhost:12345/hello

http.ResponseWriter
这是一个接口:
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
定义如下:

type ResponseWriter interface {

         Header() Header    

         WriteHeader(http.StatusOK)

         Write([]byte) (int, error)

         WriteHeader(int)
    }

*http.Request
这是一个结构:
A Request represents an HTTP request received by a server or to be sent by a client.
定义如下:

 type Request struct {
            Method string
            URL *url.URL
            Proto      string // "HTTP/1.0"
            ProtoMajor int    // 1
            ProtoMinor int    // 0
            Header Header
            Body io.ReadCloser
            ContentLength int64
            TransferEncoding []string
            Close bool
            Host string
            Form url.Values
            PostForm url.Values
            MultipartForm *multipart.Form
            Trailer Header
            RemoteAddr string
            RequestURI string
            TLS *tls.ConnectionState
    }

Get

package main

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

func main() {
    response, err := http.Get("https://www.google.com")
    if err != nil {
        // handle error
    }

    defer response.Body.Close()

    body, _ := ioutil.ReadAll(response.Body)
    fmt.Println(string(body))
}

Post

package main

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

func main() {
    body := "{\"action\":20}"
    res, err := http.Post("http://xxx.com", "application/json;charset=utf-8", bytes.NewBuffer([]byte(body)))
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }

    defer res.Body.Close()

    content, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }

    fmt.Println(string(content))
}

PostForm

resp, err := http.PostForm("http://example.com/form",
    url.Values{"key": {"Value"}, "id": {"123"}})

接下来,会跟大家介绍golang实现简单的restful api,很简单的呦!

Go语言学习之net/http包(The way to go)_第1张图片

你可能感兴趣的:(go,Go从入门到不放弃)