Upload
satoshi-satoshi
View
12.961
Download
5
Embed Size (px)
DESCRIPTION
Go lang net, net/http, net/url package の説明会資料
Citation preview
Gunosy.go #6
net/http + net/url
自己紹介
• 印南 聡志 ( いんなみ さとし )
• 6 月に Gunosy に入社
• https://github.com/satoshi03
• Java/Ruby … 最近 Python/Go 始めました
Package net/http + net/url
• net• net/http– cgi– cookiejar– httptest– httputil– pprof
• net/url
物理層
データリンク層
ネットワーク層 (IP)
トランスポート層 (TCP/UDP)
アプリケーション層 (HTTP)
Package net
• Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
• 比較的低レイヤーの通信を実現
物理層
データリンク層
ネットワーク層 (IP)
トランスポート層 (TCP/UDP)
アプリケーション層 (HTTP)
Package net
Server Client
Listen()
Accept()
Dial()
Write()
Read()
Write()
Read()
net server
• func Listen(network, laddr string) (Listener, error)– クライアントからのコネクションするための接続口を
作成– laddr : ローカルアドレス– network : “tcp”, “tcp4”, “tcp6”, “unix”, “unixpacket”
• 指定可能 : stream oriented なもの• それ以外 : エラー
– Example :• Listen(“tcp” “:8080”)
net client
• func Dial(network, address string) (Conn, error)– 指定したアドレスに network で指定した方法
( Protocol)≒ で接続– Network に指定する値
• tcp, tcp4, tcp6m udp, udp4, udp6, ip, ip4, ip6, unix, unixgram, unixpacket
– Examples• Dial(“tcp”, “12.34.56.78:80”)• Dial(“tcp”, “google.com:http”)• Dial(“tcp”, “[2001:db8::1]:http”)• Dial(“tcp”, “[fe80::1%lo0]:80”)
net server
• Func Accept(network, address string) (Conn, error)– クライアントからの接続を受諾し、 Conn オブジェク
トを返信– network : “tcp”, “tcp4”, “tcp6”, “unix”, “unixpacket”
• 指定可能 : stream oriented なもの• それ以外 : エラー
Demo
Package http
• Package http provides HTTP client and server implementations.
物理層
データリンク層
ネットワーク層 (IP)
トランスポート層 (TCP/UDP)
アプリケーション層 (HTTP)
Package http
http.Server
http.Handler
http.Client
ListenAndServe:80
GET/POST/HEAD
http server
• type Server
type Server struct { Addr string Handler Handler ReadTimeout time.Duration WriteTimeout time.Duration MaxHeaderBytes int TLSConfig *tls.Confis}
http server
func ListenAndServe(addr string, handler Handler) error– 指定したアドレス、ハンドラーを使用して
サーバーを起動
type Handler interface { ServeHTTP(ResponseWriter, *Request)}
http server demo
type AppHandler struct { } func(index *AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, »hello world »)}func main() { index := new(AppHandler) http.ListenAndServe(":8080", index) }
Package http
http.Server
http.Handler http.Handler http.Handler
http.Client
ListenAndServe:80
GET/POST/HEAD
http.ServeMux
http server
• func Handle(pattern string, handler Handler)– 指定したパターンでハンドラーを追加
• func HandleFunc(pattern string, handler func(ResponseWriter, *Request))– 指定したパターンでファンクションハンドラーを追加
http server demotype IndexHandler struct { } func(index *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This is index page.”) }type DetailHandler struct { } func(index *DetailHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This is detail page.") ↲} func main() { index := new(IndexHandler) ↲ detail := new(DetailHandler) ↲ http.Handle("/", index) http.Handle("/detail", detail) http.ListenAndServe(":8080", nil) }
http client (1/3)
• func (c *Client) Get(url string) (resp *Response, err error)– 指定した URL に対して GET リクエストを送信してレ
スポンスを取得– url : URL 文字列
http client(2/3)
• func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)– 指定した URL に対して POST リクエストを送信– url : url 文字列– bodyType : post 時に送信するバイト列の種類– body : 送信するバイト列– Example:• resp, err := http.Post(“http://example.com/upload",
"image/jpeg", &buf)
http client(3/3)
• func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)– Key Value 形式で POST リクエストを送信– url : url 文字列– data : key value 形式のデータ
• Example– resp, err := http.PostForm("http://example.com/form",
url.Values{"key": {"Value"}, "id": {"123"}})
Package url
• URL を管理するパッケージ– URL のパース– クエリーのエスケープ処理
type url
type URL struct { Scheme string Opaque string // encoded opaque data User *Userinfo // username and password information Host string // host or host:port Path string RawQuery string // encoded query values, without '?' Fragment string // fragment for references, without '#'}
scheme://[userinfo@]host/path[?query][#fragment]
url
• func Parse(rawurl string) (url *URL, err error)– URL 文字列をパースして URL オブジェクトを取得
u, err := url.Parse("http://bing.com/search?q=dotnet")if err != nil {
log.Fatal(err)}u.Scheme = "https”u.Host = "google.com”q := u.Query()q.Set("q", "golang")u.RawQuery = q.Encode()fmt.Println(u)
> https://google.com/search?q=golang
http://play.golang.org/p/8Id1F0vfvD
url• QueryEscape(s string) string– クエリーの文字列のエスケープに変換
• QueryUnescape(s string) (string, error)– エスケープされたクエリーを文字列に変換
escaped_url := url.QueryEscape(http://bing.com/search?q=test)fmt.Println("escaped_url : " + escaped_url)unescaped_url, err := url.QueryUnescape(escaped_url)if err != nil {
log.Fatal(err)}fmt.Println("escaped_url : " + unescaped_url)
escaped_url : http%3A%2F%2Fbing.com%2Fsearch%3Fq%3Dtestescaped_url : http://bing.com/search?q=test
http://play.golang.org/p/-jZzlqHdXm
Package net
• net• net/http– cgi– cookiejar– httptest– httputil– pprof
• net/url
物理層
データリンク層
ネットワーク層 (IP)
トランスポート層 (TCP/UDP)
アプリケーション層 (HTTP)