Go语言实践Go

使用 gorpc 开发 http 服务

2020-04-01  本文已影响0人  DIU哥

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

上一篇下一篇

猜你喜欢

热点阅读