This repository has been archived on 2024-04-25. You can view files and clone it, but cannot push or open issues or pull requests.
golang-rest-example/cmd/server.go

69 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-02-01 18:57:25 +00:00
package main
import (
2024-02-02 14:39:13 +00:00
"fmt"
2024-02-01 18:57:25 +00:00
"log"
"net/http"
"github.com/mentos1386/golang-rest-example/pkg/api"
2024-02-01 22:09:09 +00:00
"github.com/mentos1386/golang-rest-example/pkg/openapi"
2024-02-02 14:39:13 +00:00
"github.com/ogen-go/ogen/middleware"
"github.com/rs/cors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
2024-02-01 18:57:25 +00:00
)
2024-02-02 14:39:13 +00:00
func Logging(logger *zap.Logger) middleware.Middleware {
return func(
req middleware.Request,
next func(req middleware.Request) (middleware.Response, error),
) (middleware.Response, error) {
logger := logger.With(
zap.String("operation", req.OperationName),
zap.String("operationId", req.OperationID),
)
logger.Info("Handling request")
resp, err := next(req)
if err != nil {
logger.Error("Fail", zap.Error(err))
} else {
var fields []zapcore.Field
// Some response types may have a status code.
// ogen provides a getter for it.
//
// You can write your own interface to match any response type.
if tresp, ok := resp.Type.(interface{ GetStatusCode() int }); ok {
fields = []zapcore.Field{
zap.Int("status_code", tresp.GetStatusCode()),
}
}
logger.Info("Success", fields...)
}
return resp, err
}
}
2024-02-01 18:57:25 +00:00
func main() {
2024-02-02 14:39:13 +00:00
service := api.NewApiService()
logger, _ := zap.NewDevelopment()
2024-02-01 18:57:25 +00:00
2024-02-02 14:39:13 +00:00
srv, err := openapi.NewServer(service, openapi.WithMiddleware(Logging(logger)))
2024-02-01 18:57:25 +00:00
if err != nil {
log.Fatal(err)
}
2024-02-02 14:39:13 +00:00
address := fmt.Sprintf(":%d", service.Config.Port)
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
})
logger.Info("Starting server", zap.String("address", address))
if err := http.ListenAndServe(address, c.Handler(srv)); err != nil {
2024-02-01 18:57:25 +00:00
log.Fatal(err)
}
}