Skip to content

Commit

Permalink
重写/拆分 Gateway 实现
Browse files Browse the repository at this point in the history
  • Loading branch information
movsb committed Jun 19, 2024
1 parent 8c38925 commit 6d32d9e
Show file tree
Hide file tree
Showing 23 changed files with 420 additions and 318 deletions.
3 changes: 1 addition & 2 deletions cmd/client/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package client

import (
"context"
"fmt"
"io/fs"
"io/ioutil"
Expand Down Expand Up @@ -177,7 +176,7 @@ func AddCommands(rootCmd *cobra.Command) {
Args: cobra.NoArgs,
PreRun: preRun,
Run: func(cmd *cobra.Command, args []string) {
resp, err := client.Blog.Ping(context.Background(), &proto.PingRequest{})
resp, err := client.Blog.Ping(client.Context(), &proto.PingRequest{})
if err != nil {
panic(err)
}
Expand Down
40 changes: 40 additions & 0 deletions gateway/handlers/api/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package api

import (
"context"
"net/http"

"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/movsb/taoblog/modules/utils"
"github.com/movsb/taoblog/protocols/clients"
"github.com/movsb/taoblog/protocols/go/proto"
"google.golang.org/protobuf/encoding/protojson"
)

type _Protos struct {
mux *runtime.ServeMux
http.Handler
}

func New(ctx context.Context, client clients.Client) http.Handler {
mux := runtime.NewServeMux(
runtime.WithMarshalerOption(
runtime.MIMEWildcard,
&runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
EmitUnpopulated: true,
},
},
),
)

utils.Must(proto.RegisterUtilsHandlerClient(ctx, mux, client))
utils.Must(proto.RegisterTaoBlogHandlerClient(ctx, mux, client))
utils.Must(proto.RegisterSearchHandlerClient(ctx, mux, client))

return &_Protos{
mux: mux,
Handler: mux,
}
}
11 changes: 2 additions & 9 deletions gateway/handlers/assets/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import (
"net/http"

"github.com/movsb/taoblog/modules/utils"
"github.com/movsb/taoblog/protocols/clients"
"github.com/movsb/taoblog/protocols/go/proto"
"google.golang.org/grpc"
"nhooyr.io/websocket"
)

func New(kind string, addr string) http.Handler {
func New(kind string, client clients.Client) http.Handler {
if kind != `post` {
panic(`only for post currently`)
}
Expand All @@ -27,13 +27,6 @@ func New(kind string, addr string) http.Handler {

id := utils.MustToInt64(r.PathValue(`id`))

conn, err := grpc.DialContext(r.Context(), addr, grpc.WithInsecure())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer conn.Close()
client := proto.NewManagementClient(conn)
fs, err := client.FileSystem(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Expand Down
File renamed without changes.
File renamed without changes.
87 changes: 87 additions & 0 deletions gateway/handlers/avatar/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package avatar

import (
"context"
"io"
"net/http"

"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/movsb/taoblog/modules/utils"
"github.com/movsb/taoblog/protocols/go/proto"
"google.golang.org/grpc/status"
)

func New(server proto.TaoBlogServer) http.Handler {
return &_Avatar{
server: server,
}
}

type _Avatar struct {
server proto.TaoBlogServer
}

// Params ...
type Params struct {
Headers http.Header
}

func (h *_Avatar) ServeHTTP(w http.ResponseWriter, r *http.Request) {
emailRsp, err := h.server.GetCommentEmailById(
r.Context(),
&proto.GetCommentEmailByIdRequest{
Id: int32(utils.MustToInt64(r.PathValue(`id`))),
},
)
if err != nil {
http.Error(w, err.Error(), runtime.HTTPStatusFromCode(status.Code(err)))
return
}

p := Params{
Headers: make(http.Header),
}

for _, name := range []string{
`If-Modified-Since`,
`If-None-Match`,
} {
if h := r.Header.Get(name); h != "" {
p.Headers.Add(name, h)
}
}

// TODO 并没有限制获取未公开发表文章的评论。
rsp, err := github(context.TODO(), emailRsp.Email, &p)
if err != nil {
rsp, err = gravatar(context.TODO(), emailRsp.Email, &p)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

defer rsp.Body.Close()

// TODO:内部缓存,只正向代理 body。
for _, k := range knownHeaders {
if v := rsp.Header.Get(k); v != "" {
w.Header().Set(k, v)
}
}

// 客户端缓存失效了也可以继续用,后台慢慢刷新就行。
w.Header().Set(`Cache-Control`, `max-age=604800, stale-while-revalidate=604800`)

w.WriteHeader(rsp.StatusCode)
io.Copy(w, rsp.Body)
}

// 不再提供以下字段,官方更新太频繁,意义不大。
// `Expires`,
// `Cache-Control`,
var knownHeaders = []string{
`Content-Length`,
`Content-Type`,
`Last-Modified`,
}
13 changes: 7 additions & 6 deletions gateway/handlers/rss/rss.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"time"

"github.com/movsb/taoblog/modules/utils"
"github.com/movsb/taoblog/protocols/clients"
co "github.com/movsb/taoblog/protocols/go/handy/content_options"
"github.com/movsb/taoblog/protocols/go/proto"
)
Expand Down Expand Up @@ -44,8 +45,8 @@ type RSS struct {

LastBuildDate Date

tmpl *template.Template
svc proto.TaoBlogServer
tmpl *template.Template
client clients.Client
}

type Option func(r *RSS)
Expand All @@ -60,8 +61,8 @@ type _Config struct {
articleCount int
}

func New(svc proto.TaoBlogServer, options ...Option) http.Handler {
info := utils.Must1(svc.GetInfo(context.Background(), &proto.GetInfoRequest{}))
func New(client clients.Client, options ...Option) http.Handler {
info := utils.Must1(client.GetInfo(context.Background(), &proto.GetInfoRequest{}))

r := &RSS{
config: _Config{
Expand All @@ -73,7 +74,7 @@ func New(svc proto.TaoBlogServer, options ...Option) http.Handler {
Home: info.Home,
LastBuildDate: Date(info.LastPostedAt),

svc: svc,
client: client,
}

for _, opt := range options {
Expand All @@ -87,7 +88,7 @@ func New(svc proto.TaoBlogServer, options ...Option) http.Handler {

// ServeHTTP ...
func (r *RSS) ServeHTTP(w http.ResponseWriter, req *http.Request) {
rsp, err := r.svc.ListPosts(req.Context(), &proto.ListPostsRequest{
rsp, err := r.client.ListPosts(req.Context(), &proto.ListPostsRequest{
Limit: int32(r.config.articleCount),
OrderBy: `date desc`,
Kinds: []string{`post`},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package webhooks
package github

import (
"crypto/hmac"
Expand Down Expand Up @@ -47,8 +47,8 @@ func decode(r io.Reader, secret string, sum string) (*Payload, error) {
return &p, nil
}

func CreateHandler(secret string, reloaderPath string, sendNotify func(content string)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
func handler(secret string, reloaderPath string, sendNotify func(content string)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sum := strings.TrimPrefix(r.Header.Get(`X-Hub-Signature-256`), `sha256=`)
payload, err := decode(r.Body, secret, sum)
if err != nil {
Expand Down Expand Up @@ -85,5 +85,5 @@ func CreateHandler(secret string, reloaderPath string, sendNotify func(content s
sendNotify(fmt.Sprintf("结果未知:%s", w.Conclusion))
}
}
}
})
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package webhooks
package github

import "testing"

Expand Down
7 changes: 7 additions & 0 deletions gateway/handlers/webhooks/github/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package github

import "net/http"

func New(secret, reloaderPath string, sendNotify func(content string)) http.Handler {
return handler(secret, reloaderPath, sendNotify)
}
1 change: 1 addition & 0 deletions gateway/handlers/webhooks/grafana/all_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package grafana_test
35 changes: 35 additions & 0 deletions gateway/handlers/webhooks/grafana/grafana.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package grafana

import (
"encoding/json"
"io"
"net/http"

"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/movsb/taoblog/modules/utils"
"github.com/movsb/taoblog/protocols/go/proto"
"google.golang.org/grpc/status"
)

func New(client proto.UtilsServer) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rc := http.MaxBytesReader(w, r.Body, 1<<20)
defer rc.Close()
body := utils.DropLast1(io.ReadAll(rc))
var m map[string]any
json.Unmarshal(body, &m)
var message string
if x, ok := m[`message`]; ok {
message, _ = x.(string)
}
_, err := client.InstantNotify(r.Context(), &proto.InstantNotifyRequest{
Title: `监控告警`,
// https://grafana.com/docs/grafana/latest/alerting/configure-notifications/manage-contact-points/integrations/webhook-notifier/
Message: message,
})
if err != nil {
http.Error(w, err.Error(), runtime.HTTPStatusFromCode(status.Code(err)))
return
}
})
}
Loading

0 comments on commit 6d32d9e

Please sign in to comment.