美文网首页Go语言实践Go
使用 gorpc 开发 http 服务

使用 gorpc 开发 http 服务

作者: DIU哥 | 来源:发表于2020-04-01 23:02 被阅读0次

gorpc 是一款非常简单、易用、高性能的微服务框架,使用 gorpc 可以 分分钟开发出 http 服务。gorpc 源码非常简单,可以参考:gorpc

一、server 创建

1、第一步,创建 gorpc server ,vim server.go ,如下:


func main() {

opts := []gorpc.ServerOption{

gorpc.WithAddress("127.0.0.1:8000"),

gorpc.WithProtocol("http"),

gorpc.WithNetwork("tcp"),

gorpc.WithTimeout(time.Millisecond * 2000),

}

s := gorpc.NewServer(opts ...)

s.ServeHttp()

}

2、第二步,实现一个 http handler,如下:


func sayHello(w http.ResponseWriter, r *http.Request) {

r.ParseForm()

fmt.Println(r.Form)

fmt.Println("path", r.URL.Path)

fmt.Println("scheme", r.URL.Scheme)

fmt.Println(r.Form["url_long"])

for k, v := range r.Form {

fmt.Println("key:", k)

fmt.Println("val:", strings.Join(v, ""))

}

w.Write([]byte("world"))

}

3、第三部,路由注册


func init() {

ghttp.HandleFunc("GET","/hello", sayHello)

}

完整代码如下:


package main

import (

"fmt"

"net/http"

"strings"

"time"

"github.com/lubanproj/gorpc"

ghttp "github.com/lubanproj/gorpc/http"

)

func init() {

ghttp.HandleFunc("GET","/hello", sayHello)

}

func main() {

opts := []gorpc.ServerOption{

gorpc.WithAddress("127.0.0.1:8000"),

gorpc.WithProtocol("http"),

gorpc.WithNetwork("tcp"),

gorpc.WithTimeout(time.Millisecond * 2000),

}

s := gorpc.NewServer(opts ...)

s.ServeHttp()

}

func sayHello(w http.ResponseWriter, r *http.Request) {

fmt.Println("path", r.URL.Path)

w.Write([]byte("world"))

}

二、运行 server

运行 go run server.go ,服务在 127.0.0.1:8000 地址监听。在浏览器访问 127.0.0.1:8000 或者 curl 127.0.0.1:8000 。可以看到页面会输出 world !

详细的 demo 可以参考:http demo

相关文章

  • 使用 gorpc 开发 http 服务

    gorpc 是一款非常简单、易用、高性能的微服务框架,使用 gorpc 可以 分分钟开发出 http 服务。gor...

  • HTTP协议处理

    使用Netty服务开发。实现HTTP协议处理逻辑。

  • 前端面试2021-008

    1、如何通过NodeJS开发一个服务端应用? 使用nodejs的http内建模块开发 const http = r...

  • 什么是Nginx?

    什么是nginx? Nginx是一个http服务器(web服务器)。是一个使用c语言开发的高性能的http服务器及...

  • 通过HTTP API 方式去调用小程序的云开发

    HTTP API 提供了小程序外访问云开发资源的能力,,使用 HTTP API 开发者可在已有服务器上访问云资源,...

  • 判断微服务中的http请求来源

    使用SpringCloud做微服务开发,有时需要判断微服务中的http请求来源,判断请求是来自微服务网关转发还是来...

  • Netty4.1 HTTP开发入门

    (一)服务端 开发了一个简单的Http Server,使用的是Netty 4.1.46.Final版本。 服务器类...

  • HttpMethod自定义失败重连

    我们做web开发时,需要经常使用httpclient来请求http服务,有时为了安全起见,服务提供方会提供多个ht...

  • Nginx

    什么是nginx 是一个使用c语言开发的高性能的http服务器及反向代理服务器。Nginx是一款高性能的http ...

  • nodeJS内置模块

    1、http模块 创建服务器 使用 http.createServer() 方法创建服务器,并使用 listen ...

网友评论

    本文标题:使用 gorpc 开发 http 服务

    本文链接:https://www.haomeiwen.com/subject/hngzuhtx.html