`
sillycat
  • 浏览: 2539983 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Golang(6)Web Basic

 
阅读更多

Golang(6)Web Basic

3.1 How Go Work with Web
URL (Uniform Request Locator)
DNS (Domain Name System)
TCP ——> HTTP (80 port TCP)

Http Request 
Http Request —> Request Line, Request Header, Request Body

GET /domains/example/ HTTP/1.1   //Request Line: Request Method
Host: www.iana.org     //server host name
User-Agent              
Accept                    //Client mine
Accept-Encoding    //
Accept-Charset     //Client Charset

Body

Http Response
HTTP/1.1 200 OK   //response status Line
Server: nginx/1.0.8     //Web Server software name and version
Date: Tue, 30 Oct 2012 04:14:25 GMT //sending time
Content-Type: text/html   //Server side data mine
Transfer-Encoding: chunked //
Connection: keep-alive 
Content-Length: 90 //length of the body

<!Document html>…. Body

4XX client errors, 5XX server side errors, 2XX success, 3XX redirect, 1XX info

Keep-Alive
After HTTP/1.1, Keep-Alive will default be true. We can reuse the TCP connection. This Keep-Alive time can be set on the server side configuration.

3.2 Construct the Web Server based on Go

The Simplest Server based on http package
package main

import (
     "fmt"
     "log"
     "net/http"
     "strings"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
     r.ParseForm()                 //解析参数,默认是不会解析的
     fmt.Println("form: ", r.Form) //这些信息是输出到服务器端的打印信息
     fmt.Println("path: ", r.URL.Path)
     fmt.Println("scheme: ", r.URL.Scheme)
     fmt.Println(r.Form["url_long"])
     for k, v := range r.Form {
          fmt.Println("key:", k)
          fmt.Println("val:", strings.Join(v, ""))
     }
     fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
}

func main() {
     http.HandleFunc("/", sayhelloName)       //设置访问的路由
     err := http.ListenAndServe(":9090", nil) //设置监听的端口
     if err != nil {
          log.Fatal("ListenAndServe: ", err)
     }
}

Visit the http://localhost:9090 to see the result.

3.3 Further Work to Build Web
Some Concepts from Server Side
Request, Response, Connection, Handler

How http Package Works
for {
     rw, e := l.Accept()
     if e != nil {
     }
     c, err := srv.newConn(rw)
     if err != nil {
          continue
     }
     go c.serve()
}

handler is the second parameter of ListenAndServe, if it is nil, we will use handler = DefaultServeMux

3.4 Details of http Package
There are 2 key functions in http: Conn, ServeMux

Conn and Concurrence
c, err := srv.newConn(rw)
if err != nil {
     continue
}
go c.serve()

Customer ServeMux
How the old codes work

type ServeMux struct {
     mu sync.RWMutex //lock
     m map[string]muxEntry
     hosts bool // if put the host in the mapping rules
}

type muxEntry struct {
     explicit bool //match exactly
     h Handler
     pattern string
}

type Handler interface {
     ServeHTTP(ResponseWriter, *Request)
}

When we call method HandlerFuc, it will convert the function to contains method ServHTTP

type HandlerFunc func(ResponseWriter, *Request)

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
     f(w,r)
}

Map the Rules and then Call the Handler

Customer Mapping
package main

import (
     "fmt"
     "net/http"
)

type MyMux struct {
}

func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
     if r.URL.Path == "/" {
          sayhelloName(w, r)
          return
     }
     http.NotFound(w, r)
     return
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
     fmt.Fprintf(w, "Hello myroute!")
}

func main() {
     mux := &MyMux{}
     http.ListenAndServe(":9090", mux)
}

4. Forms
…snip...

References:
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/03.0.md

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics