golang 实现一个restful微服务的操作

如何用net/http构建一个简单的web服务

Golang提供了简洁的方法来构建web服务

package main
import (
    "net/http"
)

func HelloResponse(rw http.ResponseWriter, request *http.Request) {
    fmt.Fprintf(w, "Hello world.")
}

func main() {
    http.HandleFunc("/", HelloResponse)
    http.ListenAndServe(":3000", nil)
}

其中核心的两个方法:

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)):HandleFunc注册一个handler function对应到给定的pattern。

func ListenAndServe(addr string, handler Handler) error:ListenAndServe监听给定的TCP网络地址,接着带上handler调用Serve方法来接收请求。

在go build之后,执行编译后的文件就能在客户端看到hello world了

有了web服务,就可以制定小目标了

我认为作为第一版本,不需要复杂的设计,只需要接收到用户的请求,并且找到对应的handler,执行其逻辑,然后返回JSON响应就好了。

小目标有了,那怎么实现呢?

1.设计用户如何注册Controller和Action

据我观察,一些框架是在Controller里预先设定了GET,POST,PUT等一系列方法,负责接收GET,POST,PUT的HTTP请求。

我认为这样设计的确有其优势,因为用户只需要实现这些方法就好了,但在业务层面也有其劣势,因为我们没有办法保证负责一个页面或者功能的Controller只接收一个GET请求,如果有2个GET请求,那就需要再建立一个Controller,单单实现其GET方法。

因此我借鉴了PHP社区中Laravel注册Controller和Action的语法:Get("/", "IndexController@Index")。

用户只需要定义:

type IndexController struct {
}

func (IndexController *IndexController) Index(//params) (//return values) {
}

当然这样思考后,就给框架带入了一点动态脚本语言的特性,肯定会用到Golang的reflect库。

2.设计Path和Controller还有Action的关系容器

我运用了Golang的map,定义了map[string]map[string]map[string]string这样的数据结构

以["/":["GET":["IndexController":"Get"], "POST":["IndexController":"Post"]], "/foo":["GET":["IndexController":"Foo"]]]举例:

这个说明了在"/"这个PATH下面,有GET和POST请求,分别对应了IndexController下的Get和Post方法,在"/foo"这个PATH下面,有GET请求,对应IndexController下的Foo方法。

在接受请求时候,如果没有找到对应的方法,就返回405。

3.如何将注册了的一系列Method与PATH绑定来接收外部请求

我们可以看到,func HandleFunc(pattern string, handler func(ResponseWriter, *Request))要求的handler类型是func(ResponseWriter, *Request)),这和我们设计的functionfunc (IndexController *IndexController) Index(//params) (//return values) {}有所差距。

这时候我发现由于Golang具备First Class Functions特性,因此我们可以将函数做如下处理:

http.HandleFunc(path, HandleRequest())
func HandleRequest() {
    return func(rw http.ResponseWriter, request *http.Request) {
        // do your logic
    }
}

4.和encoding/json说Hi

当我们接收到function的返回值后,我们就需要对结果进行json encode,而encoding/json正是负责这个功能。 我用的是json.Marshal():

func Marshal(v interface{}) ([]byte, error): Marshal返回v的encoding结果。

如何使用

package main
import (
    "net/url"
    "net/http"
    "github.com/ZhenhangTung/GoGym"
)

type IndexController struct {
}

func (IndexController *IndexController) Index(request map[string]url.Values, headers http.Header) (statusCode int, response interface{}) {
    return 200, map[string]string{"hello": "world"}
}

type BarController struct {
}

func (*BarController) Bar(request map[string]url.Values, headers http.Header) (statusCode int, response interface{}, responseHeader http.Header) {
    return 200, map[string]string{"GoTo": "Bar"}, http.Header{"Foo": {"Bar", "Baz"}}
}

func main() {
    var apiService = GoGym.Prepare()
    apiService.Get("index", "IndexController@Index")
    apiService.Post("bar", "BarController@Bar")
    controllers := []interface{}{&IndexController{}}
    apiService.RegisterControllers(controllers)
    apiService.RegisterController(&BarController{})
    apiService.Serve(3000)
}

项目完整代码

package GoGym
import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
    "reflect"
    "strings"
)

const (
    GETMethod     = "GET"
    POSTMethod    = "POST"
    PUTMethod     = "PUT"
    PATCHMethod   = "PATCH"
    DELETEMethod  = "DELETE"
    OPTIONSMethod = "OPTIONS"
)

const (
    HTTPMethodNotAllowed = 405
)

// APIService for now is the struct for containing controllerRegistry and registeredPathAndController,
// and it is the core service provider
type APIService struct {
    // controllerRegistry is where all registered controllers exist
    controllerRegistry map[string]interface{}
    //registeredPathAndController is a mapping of paths and controllers
    registeredPathAndController map[string]map[string]map[string]string
    requestForm                 map[string]url.Values
}

func (api *APIService) Get(path, controllerWithActionString string) {
    mapping := api.mappingRequestMethodWithControllerAndActions(GETMethod, path, controllerWithActionString)
    api.registeredPathAndController[path] = mapping
}

func (api *APIService) Post(path, controllerWithActionString string) {
    mapping := api.mappingRequestMethodWithControllerAndActions(POSTMethod, path, controllerWithActionString)
    api.registeredPathAndController[path] = mapping
}

func (api *APIService) Put(path, controllerWithActionString string) {
    mapping := api.mappingRequestMethodWithControllerAndActions(PUTMethod, path, controllerWithActionString)
    api.registeredPathAndController[path] = mapping
}

func (api *APIService) Patch(path, controllerWithActionString string) {
    mapping := api.mappingRequestMethodWithControllerAndActions(PATCHMethod, path, controllerWithActionString)
    api.registeredPathAndController[path] = mapping
}

func (api *APIService) Options(path, controllerWithActionString string) {
    mapping := api.mappingRequestMethodWithControllerAndActions(OPTIONSMethod, path, controllerWithActionString)
    api.registeredPathAndController[path] = mapping
}

func (api *APIService) Delete(path, controllerWithActionString string) {
    mapping := api.mappingRequestMethodWithControllerAndActions(DELETEMethod, path, controllerWithActionString)
    api.registeredPathAndController[path] = mapping
}

// mappingRequestMethodWithControllerAndActions is a function for mapping request method with controllers
// which containing actions
func (api *APIService) mappingRequestMethodWithControllerAndActions(requestMethod, path, controllerWithActionString string) map[string]map[string]string {
    mappingResult := make(map[string]map[string]string)
    if length := len(api.registeredPathAndController[path]); length > 0 {
        mappingResult = api.registeredPathAndController[path]
    }
    controllerAndActionSlice := strings.Split(controllerWithActionString, "@")
    controller := controllerAndActionSlice[0]
    action := controllerAndActionSlice[1]
    controllerAndActionMap := map[string]string{controller: action}
    mappingResult[requestMethod] = controllerAndActionMap
    return mappingResult
}

// HandleRequest is a function to handle http request
func (api *APIService) HandleRequest(controllers map[string]map[string]string) http.HandlerFunc {
    return func(rw http.ResponseWriter, request *http.Request) {
        request.ParseForm()
        method := request.Method
        api.requestForm["query"] = request.Form
        api.requestForm["form"] = request.PostForm
        macthedControllers, ok := controllers[method]
        if !ok {
            rw.WriteHeader(HTTPMethodNotAllowed)
        }
        for k, v := range macthedControllers {
            controllerKey := "*" + k
            controller := api.controllerRegistry[controllerKey]
            in := make([]reflect.Value, 2)
            in[0] = reflect.ValueOf(api.requestForm)
            in[1] = reflect.ValueOf(request.Header)
            returnValues := reflect.ValueOf(controller).MethodByName(v).Call(in)
            statusCode := returnValues[0].Interface()
            intStatusCode := statusCode.(int)
            response := returnValues[1].Interface()
            responseHeaders := http.Header{}
            if len(returnValues) == 3 {
                responseHeaders = returnValues[2].Interface().(http.Header)
            }
            api.JSONResponse(rw, intStatusCode, response, responseHeaders)
        }
    }
}

// RegisterHandleFunc is a function registers a handle function to handle request from path
func (api *APIService) RegisterHandleFunc() {
    for k, v := range api.registeredPathAndController {
        path := k
        if !strings.HasPrefix(k, "/") {
            path = fmt.Sprintf("/%v", k)
        }
        http.HandleFunc(path, api.HandleRequest(v))
    }
}

// RegisterControllers is a function registers a struct of controllers into controllerRegistry
func (api *APIService) RegisterControllers(controllers []interface{}) {
    for _, v := range controllers {
        api.RegisterController(v)
    }
}

// RegisterControllers is a function registers a controller into controllerRegistry
func (api *APIService) RegisterController(controller interface{}) {
    controllerType := getType(controller)
    api.controllerRegistry[controllerType] = controller
}

// getType is a function gets the type of value
func getType(value interface{}) string {
    if t := reflect.TypeOf(value); t.Kind() == reflect.Ptr {
        return "*" + t.Elem().Name()
    } else {
        return t.Name()
    }
}

// Serve is a function
func (api *APIService) Serve(port int) {
    api.RegisterHandleFunc()
    fullPort := fmt.Sprintf(":%d", port)
    http.ListenAndServe(fullPort, nil)
}

// JSONResponse is a function return json response
func (api *APIService) JSONResponse(rw http.ResponseWriter, statusCode int, response interface{}, headers http.Header) {
    for k, v := range headers {
        for _, header := range v {
            rw.Header().Add(k, header)
        }
    }
    rw.Header().Add("Content-Type", "application/json")
    rw.WriteHeader(statusCode)
    rsp, err := json.Marshal(response)
    if err != nil {
        // TODO: logging error
        fmt.Println("JSON err:", err)
    }
    rw.Write(rsp)
}

// Prepare is a fucntion prepare the service and return prepared service to the user
func Prepare() *APIService {
    var apiService = new(APIService)
    apiService.controllerRegistry = make(map[string]interface{})
    apiService.registeredPathAndController = make(map[string]map[string]map[string]string)
    apiService.requestForm = make(map[string]url.Values)
    return apiService
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • 详解Go语言RESTful JSON API创建

    RESTful API在Web项目开发中广泛使用,本文针对Go语言如何一步步实现RESTful JSON API进行讲解, 另外也会涉及到RESTful设计方面的话题. 也许我们之前有使用过各种各样的API, 当我们遇到设计很糟糕的API的时候,简直感觉崩溃至极.希望通过本文之后,能对设计良好的RESTful API有一个初步认识. JSON API是什么? JSON之前,很多网站都通过XML进行数据交换.如果在使用过XML之后,再接触JSON, 毫无疑问,你会觉得世界多么美好.这里不深入JSO

  • 浅谈go-restful框架的使用和实现

    REST(Representational State Transfer,表现层状态转化)是近几年使用较广泛的分布式结点间同步通信的实现方式.REST原则描述网络中client-server的一种交互形式,即用URL定位资源,用HTTP方法描述操作的交互形式.如果CS之间交互的网络接口满足REST风格,则称为RESTful API.以下是 理解RESTful架构 总结的REST原则: 网络上的资源通过URI统一标示. 客户端和服务器之间传递,这种资源的某种表现层.表现层可以是json,文本,二进

  • golang 微服务之gRPC与Protobuf的使用

    RPC是什么? 所谓RPC(remote procedure call 远程过程调用)框架实际是提供了一套机制,使得应用程序之间可以进行通信,而且也遵从server/client模型.使用的时候客户端调用server端提供的接口就像是调用本地的函数一样. gRPC是什么? 与许多RPC系统一样,gRPC基于定义服务的思想,指定可以使用其参数和返回类型远程调用的方法.默认情况下,gRPC使用协议缓冲区作为接口定义语言(IDL)来描述服务接口和有效负载消息的结构. gRPC有什么好处以及在什么场景下

  • golang 实现一个restful微服务的操作

    如何用net/http构建一个简单的web服务 Golang提供了简洁的方法来构建web服务 package main import ( "net/http" ) func HelloResponse(rw http.ResponseWriter, request *http.Request) { fmt.Fprintf(w, "Hello world.") } func main() { http.HandleFunc("/", HelloRe

  • Go快速开发一个RESTful API服务

    目录 何时使用单体 RESTful 服务 商城单体 RESTful 服务 单体服务实现 Mall API 定义 账号模块 API 定义 订单模块 API 定义 商品模块 API 定义 生成单体服务 实现业务逻辑 总结 何时使用单体 RESTful 服务 对于很多初创公司来说,业务的早期我们更应该关注于业务价值的交付,而单体服务具有架构简单,部署简单,开发成本低等优点,可以帮助我们快速实现产品需求.我们在使用单体服务快速交付业务价值的同时,也需要为业务的发展预留可能性,所以我们一般会在单体服务中清

  • 微服务通过Feign调用进行密码安全认证操作

    微服务通过Feign调用进行密码安全认证 在项目中,微服务之间的通信也是通过Feign代理的HTTP客户端通信,为了保护我们的业务微服务不被其他非法未经允许的服务调用, 我们要进行访问授权配置! Feign是客户端配置,@FeignClient注解有个configuation属性,可以配置我们自定义的配置类,在此类中注入微服务认证拦截器 /** * 访问微服务需要密码 * @return */ @Bean public FeignBasicAuthRequestInterceptor reque

  • Spring Cloud Alibaba Nacos服务治理平台,服务注册、RestTemplate实现微服务之间访问负载均衡访问的问题

    目录 Nacos简介 ☘Spring Cloud 组件依赖版本 ☘Nacos部署 ☘访问Nacos平台 Nacos服务注册.微服务访问.负载均衡实现 nacos-consumer微服务创建 ☘nacos-provider微服务创建 测试 Nacos简介 Github:https://github.com/alibaba/nacos官网文档:https://nacos.io/zh-cn/docs/what-is-nacos.htmlNacos 提供了发现.配置和管理微服务能力,能快速实现动态服务发

  • SpringCloud 分布式微服务架构操作步骤

    目录 前言 SpringCloud微服务 单体架构和微服务分布式架构 单体架构分析 微服务分布式架构分析 服务拆分和远程调用 服务拆分 案例需求准备 远程调用初步 Eureka注册中心 服务注册与负载均衡 服务注册 Ribbon负载均衡 指定负载均衡规则 Nocas 注册中心 环境配置启动服务注册 Nacos 分级存储模型与集群 负载均衡 namespace 环境隔离 统一配置管理与热更新 前言 这篇笔记文章我还是没有接上之前的java,因为我中间偷懒了,写不动了.打算先把这篇安排下,然后再把之

  • spring cloud中微服务之间的调用以及eureka的自我保护机制详解

    上篇讲了spring cloud注册中心及客户端的注册,所以这篇主要讲一下服务和服务之间是怎样调用的 不会搭建的小伙伴请参考我上一篇博客:idea快速搭建spring cloud-注册中心与注册 基于上一篇的搭建我又自己搭建了一个客户端微服务: 所以现在有两个微服务,我们所实现的就是微服务1和微服务2之间的调用 注册中心就不用多说了,具体看一下两个微服务 application.yml配置也不用说了,不知道怎么配置的请参考我上篇博客 在project-solr中的constroller中: @R

  • Spring Cloud多个微服务之间调用代码实例

    这篇文章主要介绍了Spring Cloud多个微服务之间调用代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 现在又一个学生微服务 user 和 学校微服务 school,如果user需要访问school,我们应该怎么做? 1.使用RestTemplate方式 添加config import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.spr

  • 详解redis在微服务领域的贡献

    前言 说到redis,可能大家的脑海中蹦出的关键词是:NoSQL.KV.高性能.缓存等.但今天的文章从另一个角度--微服务来展开. 这篇文章的起因也是源自一次面试经历,在面试一位来自陌陌的候选人(就是那个交友的陌陌)时,他提到一点让我觉得很有意思,他说redis在陌陌被使用的非常广泛,除了常规的缓存外,某些场景下也当NoSQL数据库来使用,还用redis作为微服务的注册中心,甚至连RPC的调用协议都用了redis协议. 注册中心 最早了解到redis可以作为注册中心是从dubbo的源码中看到,但

  • 详解利用SpringCloud搭建一个最简单的微服务框架

    Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁.决策竞选.分布式会话和集群状态管理等操作提供了一种简单的开发方式. Spring Cloud包含了多个子项目(针对分布式系统中涉及的多个不同开源产品),比如:Spring Cloud Config.Spring Cloud Netflix.Spring Cloud CloudFoundry.Spring Cloud AWS.S

随机推荐