• HandleBase句柄的5种写法


    HandleBase句柄的5种写法


    package main
    
    import (
    	"encoding/json"
    	"errors"
    	"fmt"
    	"log"
    	"net/http"
    )
    
    // 路由的第一种形式
    type Router1 struct {}
    
    func (r1 *Router1) ServeHTTP(w http.ResponseWriter,r *http.Request) {
    	type Res1 struct {
    		Msg string
    	}
    	fmt.Println("欢迎来到路由1")
    	res := &Res1{Msg:"hello router 1"}
    	marshal, _ := json.Marshal(res)
    	w.Write(marshal)
    }
    
    // 路由的第二种形式
    func Router2() http.Handler {
    	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    		fmt.Println("欢迎来到路由2")
    		type Res2 struct {
    			Msg string
    		}
    		res2 := &Res2{Msg:"touter2"}
    		marshal, _ := json.Marshal(res2)
    		w.Write(marshal)
    	})
    }
    
    func Router5(w http.ResponseWriter, r *http.Request) {
    	type Res5 struct {
    		Msg string
    	}
    	fmt.Println("欢迎来到路由5")
    	res := &Res5{Msg:"hello router 5"}
    	marshal, _ := json.Marshal(res)
    	w.Write(marshal)
    }
    
    func main() {
    	http.Handle("/router1", new(Router1))
    	http.Handle("/router2", Router2())
    	// 第三种路由
    	handler3 := func(http.ResponseWriter, *http.Request) {
    		type Res3 struct {
    			Msg string
    		}
    		fmt.Println("欢迎来到路由3")
    		//res := &Res3{Msg:"hello router 3"}
    		//marshal, _ := json.Marshal(res)
    		//w.Write(marshal)
    	}
    	http.HandleFunc("/router3", handler3)
    	http.HandleFunc("/router4", func(w http.ResponseWriter, r *http.Request) {
    		type Res4 struct {
    			Msg string
    		}
    		fmt.Println("欢迎来到路由4")
    		res := &Res4{Msg:"hello router 4"}
    		marshal, _ := json.Marshal(res)
    		w.Write(marshal)
    	})
    	http.HandleFunc("/router5", Router5)
    	err := http.ListenAndServe(":9000", nil)
    	if err != nil {
    		log.Println(err, errors.New("服务器启动失败"))
    	}
    }
    
  • 相关阅读:
    Java集合
    插入排序
    修改button的可点击区域
    这就是工作
    Cocos2dx使用TextField实现输入框
    SVN解决本地版本控制与服务器版本冲突问题
    ParallaxNode视差节点实现远景近景的不同层次移动
    人生最重要的三个领域——健康、财富和爱
    什么是开发框架-- (转载)
    C++函数模版的简单使用
  • 原文地址:https://www.cnblogs.com/maomaomaoge/p/14126583.html
Copyright © 2020-2023  润新知