3.让我们的服务支持外部路由

package main

import (
    httptransport "github.com/go-kit/kit/transport/http"
    "github.com/gorilla/mux"
    "gomicro/Services"
    "net/http"
)

func main() {
    user := Services.UserService{}
    endp := Services.GenUserEnPoint(user)

    serverHandler := httptransport.NewServer(endp, Services.DecodeUserRequest, Services.EncodeUserResponse) //使用go kit创建server传入我们之前定义的两个解析函数

    r := mux.NewRouter() //使用mux来使服务支持路由
    //r.Handle(`/user/{uid:\d+}`, serverHandler) //这种写法支持多种请求方法,访问Examp: http://localhost:8080/user/121便可以访问
    r.Methods("GET").Path(`/user/{uid:\d+}`).Handler(serverHandler) //这种写法限定了请求只支持GET方法
    http.ListenAndServe(":8080", r)

}

Decode函数需要重新写了,因为取参的方式变了

func DecodeUserRequest(c context.Context, r *http.Request) (interface{}, error) { //这个函数决定了使用哪个request来请求
    vars := mux.Vars(r) //通过这个返回一个map,map中存放的是参数key和值,因为我们路由地址是这样的/user/{uid:\d+},索引参数是uid,访问Examp: http://localhost:8080/user/121,所以值为121
    if uid, ok := vars["uid"]; ok { //
        uid, _ := strconv.Atoi(uid)
        return UserRequest{Uid: uid}, nil
    }
    return nil, errors.New("参数错误")
}




猜你喜欢

转载自www.cnblogs.com/hualou/p/12076391.html
今日推荐