refactor: 重构项目结构
- 将server端相关依赖单独防止在server中
This commit is contained in:
2
interval/server/api/handler/doc.go
Normal file
2
interval/server/api/handler/doc.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package handler contains HTTP request handlers for the REST API.
|
||||
package handler
|
||||
10
interval/server/api/handler/health.go
Normal file
10
interval/server/api/handler/health.go
Normal file
@ -0,0 +1,10 @@
|
||||
package handler
|
||||
|
||||
import "net/http"
|
||||
|
||||
func Health(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := w.Write([]byte("OK")); err != nil {
|
||||
http.Error(w, "failed to write response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
47
interval/server/api/handler/push.go
Normal file
47
interval/server/api/handler/push.go
Normal file
@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.jinshen.cn/remilia/push-server/interval/server/api/dto"
|
||||
"git.jinshen.cn/remilia/push-server/interval/server/model"
|
||||
"git.jinshen.cn/remilia/push-server/interval/server/ws"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func PushHandler(hub *ws.Hub) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
topicStr := chi.URLParam(r, "topic")
|
||||
topic := model.Topic(topicStr)
|
||||
if !topic.Valid() {
|
||||
http.Error(w, "invalid topic", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.PublishRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.Content == "" {
|
||||
http.Error(w, "content cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
msg := model.Message{
|
||||
Topic: topic,
|
||||
Content: []byte(req.Content),
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
|
||||
if err := hub.BroadcastMessage(r.Context(), msg); err != nil {
|
||||
http.Error(w, "request cancelled", http.StatusRequestTimeout)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user