码迷,mamicode.com
首页 > Web开发 > 详细

响应http的三种方法

时间:2017-12-29 16:57:07      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:中介   实现   type   不为   struct   fun   lis   new   var   

小编最近再看无闻的goweb视屏,总结视屏中三种go响应http的方法

 

1.直接用  http.HandleFunc()  函数

技术分享图片
// object project main.go
package main

import (
    "io"
    "log"
    "net/http"
)

func main() {

    http.HandleFunc("/", sayhello)
    // 第一个参数代表访问的路径,第二个代表要执行的函数的名字
    
    err := http.ListenAndServe(":8080", nil)
    //设置端口号,第二个暂时没有,写为nil,在接下来的方法中介绍
    if err != nil {
        log.Fatal(err)
        //如果err不为空,打印err
    }

}

//ResponseWriter为接口,Request为结构体
func sayhello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "hello!this is version 1")
}
View Code

2.介绍Handle方法

技术分享图片
package main // dealFile project main.go

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    //首先实现 NewServeMux()方法
    max := http.NewServeMux()

    max.Handle("/", &myHandler{})
    max.HandleFunc("/hello", sayhello)

    //静态文件的实现
    wd, err := os.Getwd()
    if err != nil {
        log.Fatal(err)
    }

    max.Handle("/static/",
        http.StripPrefix("/static/",
            http.FileServer(http.Dir(wd))))

    //设置监听的端口号
    err = http.ListenAndServe(":8080", max)
    if err != nil {
        log.Fatal(err)
    }

}

type myHandler struct{}

//实现ServeHTTP方法
func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "URL:"+r.URL.String())
}

func sayhello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello world,this is version 2")
}
View Code

3.Server

技术分享图片
package main

import (
    "io"
    "log"
    "net/http"
    "time"
)

var mux map[string]func(http.ResponseWriter, *http.Request)

func main() {
    server := http.Server{
        Addr:        ":8080", //端口号
        Handler:     &myHandler{},  //实现的Handler
        ReadTimeout: 5 * time.Second,  //响应等待时间
    }

    mux = make(map[string]func(http.ResponseWriter, *http.Request))
    mux["/hello"] = sayHello
    mux["/bye"] = sayBye

    err := server.ListenAndServe()
    if err != nil {
        log.Fatal(err)
    }
}

type myHandler struct{}

func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    //判断URL是否为空并输出
    if h, ok := mux[r.URL.String()]; ok {
        h(w, r)
        return
    }
    io.WriteString(w, "URL:"+r.URL.String())
}

func sayHello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Hello World")
}

func sayBye(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "Bye Bye")
}
View Code

 

响应http的三种方法

标签:中介   实现   type   不为   struct   fun   lis   new   var   

原文地址:https://www.cnblogs.com/limozi/p/8145139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!