Go语言web开发

5,977 views

Published on

2011年3月,珠三角技术沙龙深圳小沙龙主题

Published in: Technology
0 Comments
9 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,977
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
73
Comments
0
Likes
9
Embeds 0
No embeds

No notes for slide

Go语言web开发

  1. 1. Go语言WEB开发 韦光京 2011.3.26
  2. 2. Go语言简介• Go语言是一种通用编程语言• 杀手锏: – 注重简单 – 简单易学 – 自动内存管理和轻量级语法 – 使用方便 – 快速编译 – 性能可以和C比 – 并发支持 – 可以写出更简洁的代码 – 静态类型 – 精巧、一致的标准库 – 出色的文档 – 免费、开发源码(BSD授权)
  3. 3. Go的Web开发支持• 两种模式• 一:用Go语言开发后端,其他语言做前端• 二:前端也用Go语言开发
  4. 4. 模式一• Javascript、Python、Java、PHP、Ruby... 开发前端• 通过JSON/XML/Websocket/RPC连接Go语 言开发的后端服务• 可以充分利用Go语言在开发并发网络服务 方面优势,又可以结合现有成熟Web框架 的便利
  5. 5. 模式二• 内置的http包• Web.go(类似web.py)• Twister (类似Tornado)
  6. 6. 模板• 内置template包• 其他第三方template包 – mustache
  7. 7. 数据库• sqlite3• mysql• postgrsql• ODBC• mongodb• redist• ...
  8. 8. 部署• http包内置http/https服务器• http包内置CGI• fastcgi
  9. 9. http包实战• Helloworld package main import ( "http" "io" "log" ) // 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) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatal("ListenAndServe: ", err.String()) } }
  10. 10. • Helloworld(TLS) import ( "http" "log" ) func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("This is an example server.n")) } func main() { http.HandleFunc("/", handler) log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/") err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) if err != nil { log.Fatal(err) } }
  11. 11. Http Handler• 接口: type Handler interface { ServeHTTP(ResponseWriter, *Request) } type HandlerFunc func(ResponseWriter, *Request)• 注册: func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  12. 12. FileServer例子// deliver files from the directory /var/wwwfileServer := http.FileServer("/var/www", "/")// register the handler and deliver requests to iterr := http.ListenAndServe(":8000", fileServer)if err != nil { log.Fatal(err)
  13. 13. Requesttype Request struct { Method string // GET, POST, PUT, etc. RawURL string // The raw URL given in the request. URL *URL // Parsed URL. Proto string // "HTTP/1.0" ContentLength int64 Header Header Cookie []*Cookie Body io.ReadCloser TransferEncoding []string Close bool ...}func ReadRequestfunc (*Request) FormValuefunc (*Request) MultipartReaderfunc (*Request) ParseFormfunc (*Request) ProtoAtLeastfunc (*Request) Writefunc (*Request) WriteProxy
  14. 14. Responsetype Response struct { Status string // e.g. "200 OK" StatusCode int // e.g. 200 Proto string // e.g. "HTTP/1.0" RequestMethod string // e.g. "HEAD", "CONNECT", "GET", etc. Header Header SetCookie []*Cookie Body io.ReadCloser ContentLength int64 TransferEncoding []string Close bool Trailer Header}func Getfunc Headfunc Postfunc PostFormfunc ReadResponsefunc (*Response) ProtoAtLeastfunc (*Response) Write
  15. 15. URLscheme://[userinfo@]host/path[?query][#fragment]type URL struct { Raw string // the original string Scheme string // scheme RawAuthority string // [userinfo@]host RawUserinfo string // userinfo Host string // host RawPath string // /path[?query][#fragment] Path string // /path OpaquePath bool // path is opaque (unrooted when scheme is present) RawQuery string // query Fragment string // fragment}func ParseRequestURLfunc ParseURLfunc ParseURLReferencefunc (*URL) IsAbsfunc (*URL) ParseURLfunc (*URL) ResolveReferencefunc (*URL) String
  16. 16. Form• request.Form – Form map[string][]string• request.ParseForm• request.FormValue – FormValue(key string) string
  17. 17. Cookietype Cookie struct { Name string Value string Path string Domain string Expires time.Time RawExpires string MaxAge int Secure bool HttpOnly bool Raw string Unparsed []string // Raw text of unparsed attribute-value pairs}• request.Cookie• response.SetCookie
  18. 18. template• 源于JsonTemplate• 示例: edit.html: <h1>Editing {Title}</h1> <form action="/save/{Title}" method="POST"> <div><textarea name="body" rows="20" cols="80">{Body|html}</textarea></div> <div><input type="submit" value="Save"></div> </form> code: t, _ := template.ParseFile("edit.html", nil) // template.Parse(string) t.Execute(w, p)
  19. 19. 中文处理• Go对unicode支持非常好,默认utf-8• GBK/GB2312需要第三方支持 – go-iconv
  20. 20. 总结• Go语言和相关包还在快速演化中 – 最近Brad Fitzpatrick等正在改进http包• 未来会有越来越多支持,越来越方便 – 类似Django的框架最终会出现• Go语言Web开发,相当的简单,相当的有 前途
  21. 21. 谢谢!• Email&Gtalk: vcc.163@gmail.com

×