Golang(6)Web Basic

Golang Web 开发基础
本文介绍了使用Golang进行Web开发的基本概念和技术细节,包括如何处理HTTP请求与响应、搭建简单的Web服务器,并深入探讨了http包的工作原理及自定义路由处理。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值