Hertz使用

Hello World

func main() {
h := server.Default()

h.GET("/hello", func(c context.Context, ctx *app.RequestContext) {
ctx.Data(consts.StatusOK, consts.MIMETextPlain, []byte("Hello World!"))
})

h.Spin()
}
$ go run main.go

IDL

Thrift

# echo.thrift
namespace go api

struct Request {
1: string message
}

struct Response {
1: string message
}

service Echo {
Response echo(1: Request req)
}

CloudweGo代码生成

go install github.com/cloudwego/thriftgo@latest

mkdir -p demo/demo_thrift
cd demo/demo_thrift
cwgo server --type RPC \
--module demo/demo_thrift \
--service demo_thrift \
--idl ../../echo.thrift

Protobuf

syntax = "proto3"

package pbapi;

option go_package = "/pbapi";

message Request {
string msg = 1;
}

message Response {
string msg = 1;
}

service EchoService {
rpc Echo (Request) returns (Response) {}
}

CloudweGo代码生成

mkdir -p demo/demo_proto
cd demo/demo_proto

cwgo server -I ../../idl
--type RPC \
--module demo/demo_proto \
--service demo_proto \
--idl ../../echo.thrift

MakeFile自动cwgo代码生成

.PHONY: gen-demo-proto
gen-demo-proto:
@cd demo/demo_proto && cwgo server -I ../../idl --type RPC --module demo/demo_proto --service demo_proto --idl ../../echo.thrift

Consul服务注册、发现

服务注册用于为服务集群提供统一接口,自动处理集群loadbalance和宕机

// r, err := consul.NewConsulRegister("localhost:8500")
r, err := consul.NewConsulRegister(conf.Getconf().Registry.RegistryAddress[0])
if err != nil {
log.Fatal(err)
}
opts = append(opts, server.WithRegistry(r))
version: '3'
services:
consul:
ports:
- 8500:8500

Gorm操作数据库

package model

import "gorm.io/gorm"

type User struct {
gorm.Model
Email string `gorm:"uniqueIndex;type:varchar(128) not null"`
Password string `gorm:"type:varchar(64) not null"`

}

新增页面

  • 路由
// main.go
func main() {
...
h.GET("/your-page", func(c context.Context, ctx *app.RequestContext) {
ctx.HTML(consts.StatusOK, "your-page.tmpl", utils.H("Title: Your Title"))
})
}
  • 模板
// your-page.tmpl
{{ define "your-page" }}
<div>
...
</div>
{{ end }}
  • Hertz生成IDL接口代码
syntax = "proto3"

package pbapi;

option go_package = "/pbapi";

message Request {
string msg = 1;
}

message Response {
string msg = 1;
}

service EchoService {
rpc Echo (Request) returns (Response) {}
}