httpservice

package
v0.0.48 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2023 License: MIT Imports: 17 Imported by: 0

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

Examples

Constants

This section is empty.

Variables

View Source
var (
	MissingCredentials = errors.New("missing credentials")
)

Functions

func AuthMiddleware

func AuthMiddleware(accepted AuthKind, errorMapper AuthErrorMapper, roles ...structs.Role) func(http.Handler) http.Handler

func ParseJsonRequest

func ParseJsonRequest(r *http.Request, res proto.Message) error

ParseJsonRequest - функция парсинга запроса с помощью protojson

func ParseProtoRequest

func ParseProtoRequest(r *http.Request, res proto.Message) error

ParseProtoRequest - функция парсинга запроса с помощью proto

func ParseRequest

func ParseRequest(r *http.Request, res proto.Message) error

ParseRequest - вспомогательная функция парсинга запроса

func ParseVersionHeader

func ParseVersionHeader(header http.Header, key string) (structs.Platform, []string)

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

func VersionMiddleware(header string, checker VersionChecker) func(http.Handler) http.Handler

Types

type AuthErrorMapper

type AuthErrorMapper func(error) (int, proto.Message)

type AuthKind

type AuthKind struct {
	Basic, AuthToken, RefreshToken, Cookie bool
	CookieName                             string
}

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server - обертка надо http.Server с настройкой маршрутизации запросов

Для привязки обработчиков будет использован не корневой роутер, а роутер с префиксом consts.ApiPrefix

func NewServer

func NewServer(service Service, address string) (*Server, error)

NewServer - создание сервера

func (*Server) Start

func (s *Server) Start() error

Start - запуск сервера

func (*Server) Stop

func (s *Server) Stop() error

Stop - остановка сервера

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-запросов

type VersionChecker

type VersionChecker func(platform structs.Platform, versions []string) (int, proto.Message)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL