zoukankan      html  css  js  c++  java
  • go http的三种实现---3

    package main
    
    //效率最高的一个方法
    import (
    	"fmt"
    	"io"
    	"log"
    	"net/http"
    	"os"
    	"strings"
    	"time"
    )
    
    var mux map[string]func(http.ResponseWriter, *http.Request)
    
    func main() {
    	//声明一个server
    	server := http.Server{
    		Addr:        ":8080",         //监听端口
    		Handler:     &handler{},      //handler
    		ReadTimeout: 5 * time.Second, //监听超时
    	}
    	//路由列表
    	mux = make(map[string]func(http.ResponseWriter, *http.Request))
    	mux["/hello"] = hello
    
    	//开始监听
    	err := server.ListenAndServe()
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    
    type handler struct{}
    
    func (*handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    	//实现静态文件输出
    	if strings.Contains(r.URL.String(), "/static/") {
    		fmt.Println("111")
    		wd, err := os.Getwd()
    		if err != nil {
    			log.Fatal(err)
    		}
    		//此处使用.Serve.HTTP(w, r)的原因参考下面资料
    		http.StripPrefix("/static/", http.FileServer(http.Dir(wd))).ServeHTTP(w, r)
    		return
    	}
    	//	动态匹配路由
    	if h, ok := mux[r.URL.String()]; ok {
    		//匹配成功执行函数
    		h(w, r)
    		return
    	}
    	//	没有匹配成功则输出URL
    	io.WriteString(w, "URL:"+r.URL.String())
    }
    
    //输出hello
    func hello(w http.ResponseWriter, r *http.Request) {
    	io.WriteString(w, "hello")
    }
    

    参考资料

  • 相关阅读:
    目标检测:YOLOV2
    目标检测:YOLOV1
    格拉姆矩阵(Gram matrix)详细解读
    Java 线程Thread.Sleep详解
    luogu2429 制杖题
    luogu2441 角色属性树
    luogu2398 SUM GCD
    luogu2303 [SDOI2012] Longge的问题
    luogu2054 洗牌 同余方程
    线性同余方程
  • 原文地址:https://www.cnblogs.com/zheng-chuang/p/6083492.html
Copyright © 2011-2022 走看看