SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Go语言WEB开发

   韦光京
  2011.3.26
Go语言简介
• Go语言是一种通用编程语言
• 杀手锏:
 –   注重简单
 –   简单易学
 –   自动内存管理和轻量级语法
 –   使用方便
 –   快速编译
 –   性能可以和C比
 –   并发支持
 –   可以写出更简洁的代码
 –   静态类型
 –   精巧、一致的标准库
 –   出色的文档
 –   免费、开发源码(BSD授权)
Go的Web开发支持
• 两种模式
• 一:用Go语言开发后端,其他语言做前端
• 二:前端也用Go语言开发
模式一
• Javascript、Python、Java、PHP、Ruby...
  开发前端
• 通过JSON/XML/Websocket/RPC连接Go语
  言开发的后端服务
• 可以充分利用Go语言在开发并发网络服务
  方面优势,又可以结合现有成熟Web框架
  的便利
模式二
• 内置的http包
• Web.go(类似web.py)
• Twister (类似Tornado)
模板
• 内置template包
• 其他第三方template包
 – mustache
数据库
•   sqlite3
•   mysql
•   postgrsql
•   ODBC
•   mongodb
•   redist
•   ...
部署
• http包内置http/https服务器
• http包内置CGI
• fastcgi
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())
        }
     }
• 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)
      }
   }
Http Handler
• 接口:
  type Handler interface {
     ServeHTTP(ResponseWriter, *Request)
  }

   type HandlerFunc func(ResponseWriter, *Request)

• 注册:
  func HandleFunc(pattern string, handler
    func(ResponseWriter, *Request))
FileServer例子
// deliver files from the directory /var/www
fileServer := http.FileServer("/var/www", "/")




// register the handler and deliver requests to it

err := http.ListenAndServe(":8000", fileServer)
if err != nil {
   log.Fatal(err)
Request
type 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 ReadRequest
func (*Request) FormValue
func (*Request) MultipartReader
func (*Request) ParseForm
func (*Request) ProtoAtLeast
func (*Request) Write
func (*Request) WriteProxy
Response
type 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 Get
func Head
func Post
func PostForm
func ReadResponse
func (*Response) ProtoAtLeast
func (*Response) Write
URL
scheme://[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 ParseRequestURL
func ParseURL
func ParseURLReference
func (*URL) IsAbs
func (*URL) ParseURL
func (*URL) ResolveReference
func (*URL) String
Form
• request.Form
  – Form map[string][]string
• request.ParseForm
• request.FormValue
  – FormValue(key string) string
Cookie
type 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
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)
中文处理
• Go对unicode支持非常好,默认utf-8
• GBK/GB2312需要第三方支持
 – go-iconv
总结
• Go语言和相关包还在快速演化中
 – 最近Brad Fitzpatrick等正在改进http包
• 未来会有越来越多支持,越来越方便
 – 类似Django的框架最终会出现
• Go语言Web开发,相当的简单,相当的有
  前途
谢谢!
• Email&Gtalk: vcc.163@gmail.com

Weitere ähnliche Inhalte

Andere mochten auch (13)

ActiveConversion ProspectAlert Presentation
ActiveConversion ProspectAlert  PresentationActiveConversion ProspectAlert  Presentation
ActiveConversion ProspectAlert Presentation
 
Go
GoGo
Go
 
The Dark Side
The Dark SideThe Dark Side
The Dark Side
 
Kasal
KasalKasal
Kasal
 
Go集成c&c++代码
Go集成c&c++代码Go集成c&c++代码
Go集成c&c++代码
 
Very beautiful
Very beautifulVery beautiful
Very beautiful
 
Go
GoGo
Go
 
ActiveConversion Lead Scoring
ActiveConversion Lead ScoringActiveConversion Lead Scoring
ActiveConversion Lead Scoring
 
사계절 출판사
사계절 출판사사계절 출판사
사계절 출판사
 
Increasing Trade Show ROI
Increasing Trade Show ROIIncreasing Trade Show ROI
Increasing Trade Show ROI
 
사계절 출판사
사계절 출판사사계절 출판사
사계절 출판사
 
사계절 출판사
사계절 출판사사계절 출판사
사계절 출판사
 
Видеореклама: новые возможности, новые деньги
Видеореклама: новые возможности, новые деньгиВидеореклама: новые возможности, новые деньги
Видеореклама: новые возможности, новые деньги
 

Ähnlich wie Go语言web开发

COSCUP 2010 - node.JS 於互動式網站之應用
COSCUP 2010 - node.JS 於互動式網站之應用COSCUP 2010 - node.JS 於互動式網站之應用
COSCUP 2010 - node.JS 於互動式網站之應用
ericpi Bi
 
HTML5概览
HTML5概览HTML5概览
HTML5概览
Adam Lu
 
Lucene 全文检索实践
Lucene 全文检索实践Lucene 全文检索实践
Lucene 全文检索实践
yiditushe
 
Real time web实时信息流推送
Real time web实时信息流推送Real time web实时信息流推送
Real time web实时信息流推送
yongboy
 
Introduction to Parse JavaScript SDK
Introduction to Parse JavaScript SDKIntroduction to Parse JavaScript SDK
Introduction to Parse JavaScript SDK
維佋 唐
 
非常靠谱 Html 5
非常靠谱 Html 5 非常靠谱 Html 5
非常靠谱 Html 5
Tony Deng
 
Ajax Transportation Methods
Ajax Transportation MethodsAjax Transportation Methods
Ajax Transportation Methods
yiditushe
 
WEB 安全基础
WEB 安全基础WEB 安全基础
WEB 安全基础
xki
 

Ähnlich wie Go语言web开发 (20)

走马观花— Haskell Web 开发
走马观花— Haskell Web 开发走马观花— Haskell Web 开发
走马观花— Haskell Web 开发
 
COSCUP 2010 - node.JS 於互動式網站之應用
COSCUP 2010 - node.JS 於互動式網站之應用COSCUP 2010 - node.JS 於互動式網站之應用
COSCUP 2010 - node.JS 於互動式網站之應用
 
Php
PhpPhp
Php
 
Mopcon2014 - 使用 Sinatra 結合 Ruby on Rails 輕鬆打造完整 Full Stack 網站加 API Service服務
Mopcon2014 - 使用 Sinatra 結合 Ruby on Rails 輕鬆打造完整 Full Stack 網站加 API Service服務Mopcon2014 - 使用 Sinatra 結合 Ruby on Rails 輕鬆打造完整 Full Stack 網站加 API Service服務
Mopcon2014 - 使用 Sinatra 結合 Ruby on Rails 輕鬆打造完整 Full Stack 網站加 API Service服務
 
HTML5概览
HTML5概览HTML5概览
HTML5概览
 
Lucene 全文检索实践
Lucene 全文检索实践Lucene 全文检索实践
Lucene 全文检索实践
 
Real time web实时信息流推送
Real time web实时信息流推送Real time web实时信息流推送
Real time web实时信息流推送
 
Real-Time Web实时信息流推送
Real-Time Web实时信息流推送Real-Time Web实时信息流推送
Real-Time Web实时信息流推送
 
Introduction to Parse JavaScript SDK
Introduction to Parse JavaScript SDKIntroduction to Parse JavaScript SDK
Introduction to Parse JavaScript SDK
 
gRPC - 打造輕量、高效能的後端服務
gRPC - 打造輕量、高效能的後端服務gRPC - 打造輕量、高效能的後端服務
gRPC - 打造輕量、高效能的後端服務
 
非常靠谱 Html 5
非常靠谱 Html 5 非常靠谱 Html 5
非常靠谱 Html 5
 
Chrome插件开发
Chrome插件开发Chrome插件开发
Chrome插件开发
 
Page Object in XCUITest
Page Object in XCUITestPage Object in XCUITest
Page Object in XCUITest
 
Golang
GolangGolang
Golang
 
Ajax Transportation Methods
Ajax Transportation MethodsAjax Transportation Methods
Ajax Transportation Methods
 
WEB 安全基础
WEB 安全基础WEB 安全基础
WEB 安全基础
 
用JAX-RS和Jersey完成RESTful Web Services
用JAX-RS和Jersey完成RESTful Web Services用JAX-RS和Jersey完成RESTful Web Services
用JAX-RS和Jersey完成RESTful Web Services
 
Html5和css3入门
Html5和css3入门Html5和css3入门
Html5和css3入门
 
Asp.net mvc 培训
Asp.net mvc 培训Asp.net mvc 培训
Asp.net mvc 培训
 
JQuery 学习
JQuery 学习JQuery 学习
JQuery 学习
 

Go语言web开发

  • 1. Go语言WEB开发 韦光京 2011.3.26
  • 2. Go语言简介 • Go语言是一种通用编程语言 • 杀手锏: – 注重简单 – 简单易学 – 自动内存管理和轻量级语法 – 使用方便 – 快速编译 – 性能可以和C比 – 并发支持 – 可以写出更简洁的代码 – 静态类型 – 精巧、一致的标准库 – 出色的文档 – 免费、开发源码(BSD授权)
  • 4. 模式一 • Javascript、Python、Java、PHP、Ruby... 开发前端 • 通过JSON/XML/Websocket/RPC连接Go语 言开发的后端服务 • 可以充分利用Go语言在开发并发网络服务 方面优势,又可以结合现有成熟Web框架 的便利
  • 7. 数据库 • sqlite3 • mysql • postgrsql • ODBC • mongodb • redist • ...
  • 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. • 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. Http Handler • 接口: type Handler interface { ServeHTTP(ResponseWriter, *Request) } type HandlerFunc func(ResponseWriter, *Request) • 注册: func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
  • 12. FileServer例子 // deliver files from the directory /var/www fileServer := http.FileServer("/var/www", "/") // register the handler and deliver requests to it err := http.ListenAndServe(":8000", fileServer) if err != nil { log.Fatal(err)
  • 13. Request type 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 ReadRequest func (*Request) FormValue func (*Request) MultipartReader func (*Request) ParseForm func (*Request) ProtoAtLeast func (*Request) Write func (*Request) WriteProxy
  • 14. Response type 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 Get func Head func Post func PostForm func ReadResponse func (*Response) ProtoAtLeast func (*Response) Write
  • 15. URL scheme://[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 ParseRequestURL func ParseURL func ParseURLReference func (*URL) IsAbs func (*URL) ParseURL func (*URL) ResolveReference func (*URL) String
  • 16. Form • request.Form – Form map[string][]string • request.ParseForm • request.FormValue – FormValue(key string) string
  • 17. Cookie type 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. 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)
  • 20. 总结 • Go语言和相关包还在快速演化中 – 最近Brad Fitzpatrick等正在改进http包 • 未来会有越来越多支持,越来越方便 – 类似Django的框架最终会出现 • Go语言Web开发,相当的简单,相当的有 前途