go web

http请求

hello world

package main

import (
    "fmt"
    "net/http"
)

//创建处理器函数
func handler(w http.ResponseWriter,r *http.Request){
    //r.URL.Path路由中的参数
    fmt.Fprintln(w,"世界 你好",r.URL.Path)
}

func main(){
    //创建多路复用器
    mux:=http.NewServeMux()
    mux.HandleFunc("/",handler)
    //创建路由
    http.ListenAndServe(":8080",mux)

}
View Code

web服务器的创建

使用默认的多路复用器(DefaultServeMux)

1.使用处理器函数处理请求
package main

import (
    "fmt"
    "net/http"
)

//使用默认的多路服用器
//1.使用处理器函数处理请求
//创建处理器函数
func handler(w http.ResponseWriter,r *http.Request){
    fmt.Fprintln(w,"正在通过处理器函数处理您的请求")
}

func main(){
    http.HandleFunc("/",handler)
    http.ListenAndServe(":8080",nil)
}
View Code
2.使用处理器处理请求
package main

import (
    "fmt"
    "net/http"
)

//2.使用处理器处理请求

type MyHandler struct{}

func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "正在通过处理器处理您的请求")
}

func main() {
    myHandler := MyHandler{}
    //调用处理器
    http.Handle("/", &myHandler)
    http.ListenAndServe(":8080", nil)
}
View Code

3.测试通过Server结构详细配置服务器

package main

import (
    "fmt"
    "net/http"
    "time"
)

//通过Server结构对服务器进行更详细的配置

type MyHandler struct{}

func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "测试通过Server结构详细配置服务器")
}

func main() {
    myHandler := MyHandler{}
    //通过Server结构对服务器进行更详细的配置
    server := http.Server{
        Addr:        ":8080",
        Handler:     &myHandler,
        ReadTimeout: 2 * time.Second,
    }
    server.ListenAndServe()
}
View Code

使用自己创建的多路复用器

package main

import (
    "fmt"
    "net/http"
)

//使用自己创建的多路复用器

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "通过自己创建的多路复用器来处理请求")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/myMux", handler)
    http.ListenAndServe(":8080", mux)
}
View Code

未完待续。。。

猜你喜欢

转载自www.cnblogs.com/huay/p/12356144.html