Documentation ¶
Overview ¶
Package httpservice - пакет для инициализации типового http-сервера
Example ¶
package main import ( "github.com/custom-app/sdk-go/service/httpservice" "github.com/custom-app/sdk-go/service/workerpool/workerpoolhttp" "github.com/gorilla/mux" "log" "time" ) type Service struct { queue *workerpoolhttp.Queue workers []*workerpoolhttp.Worker } func (s *Service) Start() error { var err error s.queue, err = workerpoolhttp.NewQueue(&workerpoolhttp.QueueOptions{ QueueSize: 10, Timeout: time.Second, OverflowCode: 200, OverflowMsg: nil, // сообщение о переполнении OverflowMsgProto: nil, // заполнится само OverflowMsgJson: nil, // заполнится само }) if err != nil { return err } s.workers = make([]*workerpoolhttp.Worker, 4) for i := range s.workers { s.workers[i] = workerpoolhttp.NewWorker(s.queue.GetQueue()) go s.workers[i].Run() } return nil } func (s *Service) Stop() error { s.queue.Close() return nil } func (s *Service) FillHandlers(router *mux.Router) error { router.Handle("/test", nil) // запрос будет привязан к пути /api/test router.Use(s.queue.Handler) // привязка очереди запросов return nil } func (s *Service) CheckSelf() map[string]bool { return map[string]bool{} } func (s *Service) CheckOther() map[string]bool { return map[string]bool{} } func main() { s, err := httpservice.NewServer(&Service{}, "0.0.0.0:1337") if err != nil { log.Panicln(err) } go func() { if err := s.Start(); err != nil { log.Panicln(err) } }() time.Sleep(30 * time.Second) if err := s.Stop(); err != nil { log.Panicln(err) } }
Output:
Index ¶
- Variables
- func AuthMiddleware(accepted AuthKind, errorMapper AuthErrorMapper, roles ...structs.Role) func(http.Handler) http.Handler
- func ParseJsonRequest(r *http.Request, res proto.Message) error
- func ParseProtoRequest(r *http.Request, res proto.Message) error
- func ParseRequest(r *http.Request, res proto.Message) error
- func ParseVersionHeader(header http.Header, key string) (structs.Platform, []string)
- func SendBytes(w http.ResponseWriter, code int, data []byte)
- func SendJson(w http.ResponseWriter, code int, resp proto.Message)
- func SendProto(w http.ResponseWriter, code int, m proto.Message)
- func SendResponseWithContentType(w http.ResponseWriter, r *http.Request, code int, resp proto.Message)
- func VersionMiddleware(header string, checker VersionChecker) func(http.Handler) http.Handler
- type AuthErrorMapper
- type AuthKind
- type Server
- type Service
- type VersionChecker
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var (
MissingCredentials = errors.New("missing credentials")
)
Functions ¶
func AuthMiddleware ¶
func ParseJsonRequest ¶
ParseJsonRequest - функция парсинга запроса с помощью protojson
func ParseProtoRequest ¶
ParseProtoRequest - функция парсинга запроса с помощью proto
func ParseRequest ¶
ParseRequest - вспомогательная функция парсинга запроса
func ParseVersionHeader ¶
func SendBytes ¶
func SendBytes(w http.ResponseWriter, code int, data []byte)
SendBytes - отправка массива байт со статус-кодом
func SendJson ¶
func SendJson(w http.ResponseWriter, code int, resp proto.Message)
SendJson - отправка прото с помощью protojson со статус-кодом
func SendProto ¶
func SendProto(w http.ResponseWriter, code int, m proto.Message)
SendProto - отправка прото со статус-кодом
func SendResponseWithContentType ¶
func SendResponseWithContentType(w http.ResponseWriter, r *http.Request, code int, resp proto.Message)
SendResponseWithContentType - отправка ответа на запрос с проверкой Content-Type для выбора способа сериализации ответа
func VersionMiddleware ¶
Types ¶
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server - обертка надо http.Server с настройкой маршрутизации запросов
Для привязки обработчиков будет использован не корневой роутер, а роутер с префиксом consts.ApiPrefix
type Service ¶
type Service interface { Start() error // Запуск сервиса Stop() error // Остановка сервиса FillHandlers(router *mux.Router) error // Привязка обработчиков к путям CheckSelf() map[string]bool // Healthcheck для сервиса CheckOther() map[string]bool // Healthcheck интегрированных сервисов }
Service - интерфейс, определяющий обработчик http-запросов