Golang (Go Language) http detailed simple Basics (1)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Because it seems like a long time to write PHP may feel irritable, so write a little golang things you can take to play, Golang in the Web development to let you handy, in fact, is also very good things, as long as you play in after feeling good cool, feel better than the benefits of PHP is not so many "restrictions", Basic part of everyone can see the simple I then updated a little bit behind will continue to fill in, after that is Php+golang may also write some object-c, nonsense not to start writing, all the code I put on the BUYVM build goweb everyone can go to HTTP. www.lingphp.com:8080/demo/View get full code, now www.lingphp.com just get yaf frame has not done, we do not test attack play ha

web1.go

package mainimport (    "io"    "net/http")func hello(rw http.ResponseWriter, req *http.Request) {    io.WriteString(rw, "hello widuu")}func main() {    http.HandleFunc("/", hello)  //设定访问的路径    http.ListenAndServe(":8080", nil) //设定端口和handler}

This we output the Hello Word, and then we parse this from the source, we see the last main function is handlefunc this function we find the source code of this piece of code to see the following

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {    DefaultServeMux.HandleFunc(pattern, handler)}

Pattern is a string that parses the path, and then executes a handler function method, as in the example we passed in Hello, he will execute Defaultservemux, we will see the source code when the var Defaultservemux = Newservemux () Let's look at Newservemux this source code

func NewServeMux() *ServeMux {        return &ServeMux{m: make(map[string]muxEntry)} }//而里边的返回一个新的ServeMuxtype ServeMux struct {    // contains filtered or unexported fields}

So we can say the word

//申明一个ServeMux结构type MyHandler struct{}mux := http.NewServeMux()//我们可以通过一下 http提供的func Handle(pattern string, handler Handler)  //第一个是我们的路径字符串 第二个是这样的 是个接口type Handler interface {    ServeHTTP(ResponseWriter, *Request)}//实现这个接口我们就要继承ServeHTTP这个方法 所以代码func (*MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {    io.WriteString(w, "URL"+r.URL.String())}//我们查看源代码func (mux *ServeMux) Handle(pattern string, handler Handler) //这个新的ServeMux低下的Handle来设置 这里的Handler也是Handler interface所以我们将这个mux.Handle("/", &MyHandler{})mux.HandleFunc("/hello", sayHello)// 我们一样可以通过handleFunc设置//源代码func ListenAndServe(addr string, handler Handler) error http.ListenAndServe(":8080",mux) //所以我们把mux传进去

web2.go

//完整代码package mainimport (    "io"    "net/http")type MyHandle struct{}func main() {    mux := http.NewServeMux()    mux.Handle("/", &MyHandle{})    http.ListenAndServe(":8080", mux)}func (*MyHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {    io.WriteString(w, "URL"+r.URL.String())}

And then we go deeper.

Func listenandserve (addr string, handler handler) error {server: = &server{addr:addr, Handler:handler} return Server. Listenandserve ()}//returns serve we look at its structure type Server struct {Addr string//TCP address to listen on, ": htt P "If empty Handler Handler//Handler to invoke, HTTP. Defaultservemux if nil readtimeout time. Duration//maximum Duration before timing out read of the request WriteTimeout time. Duration//maximum Duration before timing out write of the response maxheaderbytes int//maximum size of RE Quest headers, defaultmaxheaderbytes if 0 tlsconfig *tls.     Config//optional TLS config, used by LISTENANDSERVETLS//Tlsnextproto Optionally specifies a function-to-take-over  Ownership of the provided TLS connection when a NPN//protocol upgrade has occurred. The map key is the protocol//name negotiated. The Handler argument should is used to//handle HTTP requests and would initialiZe the Request ' s TLS//and remoteaddr if not already set.    The connection is//automatically closed when the function returns. Tlsnextproto Map[string]func (*server, *tls. Conn, Handler)}//our own set type Myhandle struct{}server: = http. server{Addr: ": 8080", Handler: &myhandle{}, Readtimeout:6 * time. Second,}//We've looked at it. We're going to implement a route distribution map. So we see the bottom f is a Handlerfunc type func (f Handlerfunc) servehttp (w responsewriter, R *request ) {f (W, R)}//so we declare the Var mux map[string]func (http. Responsewriter, *http. Request) Mux = Make (Map[string]func (HTTP. Responsewriter, *http. Request)) mux["/hello"] = hellomux["/bye"] = byeerr: = Server. Listenandserve () if err! = Nil {log. Fatal (ERR)}//so that we can do the mapping of the path func (*myhandle) servehttp (w http. Responsewriter, R *http. Request) {if h, OK: = Mux[r.url. String ()]; OK {h (W, R)} io. WriteString (W, "URL" +r.url. String ())}func Hello (w http. Responsewriter, R *http. Request) {io. WriteString (w, "Hello module")}func bye(W http. Responsewriter, R *http. Request) {io. WriteString (W, "Bye Module")}//may be someone who does not understand mux["/hello"] = Hello then the low h (w,r) I simply explain to see an example go inside can be a type test func (int) bool//set a T An est func (int) bool type func isadd (i int) bool {if i%2 = = 0 {return false} return True}func filter (s []int        , f test) []int {var result []int for _, V: = range S {if f (v) {result = Append (result, v) }} return Result}func main () {slice: = []int{1, 2, 3, 4, 5, 6, 7, 8} B: = Filter (slice, isadd) fmt. Println (b)}//does not understand the point is actually similar to F:=FUNC (x int) {FMT. Println ("Hello")}f ();

web3.go

package mainimport (    "io"    "log"    "net/http"    "time")var mux map[string]func(http.ResponseWriter, *http.Request)func main() {    server := http.Server{        Addr:        ":8080",        Handler:     &MyHandle{},        ReadTimeout: 6 * time.Second,    }    mux = make(map[string]func(http.ResponseWriter, *http.Request))    mux["/hello"] = hello    mux["/bye"] = bye    err := server.ListenAndServe()    if err != nil {        log.Fatal(err)    }}type MyHandle struct{}func (*MyHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {    if h, ok := mux[r.URL.String()]; ok {        h(w, r)    }    io.WriteString(w, "URL"+r.URL.String())}func hello(w http.ResponseWriter, r *http.Request) {    io.WriteString(w, "hello 模块")}func bye(w http.ResponseWriter, r *http.Request) {    io.WriteString(w, "bye 模块")}

You don't know, though, it's too late, it's a little hasty.

without permission, may not reprint this station any article: the Micro Degree network»golang (go Language) HTTP detailed Simple Foundation (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.