Compare commits

..

1 Commits

Author SHA1 Message Date
448cc090d8 [feature] Added CI config
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2022-04-21 22:12:09 +02:00
19 changed files with 198 additions and 82 deletions

View File

@ -32,6 +32,7 @@ steps:
- name: build_image
image: plugins/docker
commands:
- env
- sleep 5
- ./deploy/docker/build_image.sh
depends_on:

View File

@ -7,7 +7,7 @@ race:
go run --race cmd/server/main.go
build:
GOOS=linux GOARCH=amd64 go build -o build/server cmd/server/main.go
go build -o build/server cmd/server/main.go
test:
go test -v -run=. test/**/*.go

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"log"
"net"
"os"
"os/signal"
@ -16,22 +17,20 @@ import (
const (
defHttpIp = "127.0.0.1"
defHttpPort = "8080"
defDbUrl = "postgres://postgres:postgres@127.0.0.1:5432/Api" // FIXME: use env
defDbUrl = "postgres://postgres:postgres@127.0.0.1:5432/Api" // FIXME use default container conf in future
)
func main() {
if config.ErrLoadingEnvs != nil {
app.Panicf("Error loading .env file")
log.Fatalln("Error loading .env file")
}
httpAddr := net.JoinHostPort(config.GetEnv("SERVER_IP", defHttpIp), config.GetEnv("SERVER_PORT", defHttpPort))
dbConnStr := config.GetEnv("DATABASE_URL", defDbUrl)
//fmt.Println(dbConnStr)
//os.Exit(1)
dbc, err := database.Connect(dbConnStr)
if err != nil {
app.Panicf("Unable to connect to database: %v\n", err)
log.Panicf("Unable to connect to database: %v\n", err)
}
env := &handler.Env{httpAddr, dbc}

View File

@ -1,5 +1,6 @@
#!/bin/sh
set -evx
set -e
set -x
branch=${DRONE_TAG:=$CI_COMMIT_BRANCH}
branch=$(echo $branch | grep -v /) || echo $branch ;

View File

@ -1,5 +1,6 @@
#!/bin/sh
set -evx
set -e
set -x
branch=${DRONE_TAG:=$CI_COMMIT_BRANCH}
branch=$(echo $branch | grep -v /) || echo $branch ;

2
go.mod
View File

@ -1,6 +1,6 @@
module git.pbiernat.dev/golang/rest-api-prototype
go 1.18
go 1.17
require (
github.com/go-ozzo/ozzo-validation v3.6.0+incompatible

View File

@ -1,21 +0,0 @@
#FIXME: FIX PATHS
[Unit]
Requires=network-online.target
After=network-online.target
Requires=api-server.socket
[Service]
ExecStart=/home/keedosn/go/src/git.pbiernat.dev/golang/rest-api-prototype/build/server
ExecStop=/bin/kill $MAINPID
WorkingDirectory=/home/keedosn/go/src/git.pbiernat.dev/golang/rest-api-prototype
User=keedosn
Group=keedosn
NonBlocking=true
StandardOutput=append:/home/keedosn/go/src/git.pbiernat.dev/golang/rest-api-prototype/build/api-server.log
StandardError=append:/home/keedosn/go/src/git.pbiernat.dev/golang/rest-api-prototype/build/api-server.log
SyslogIdentifier=api-server
[Install]
WantedBy=multi-user.target

View File

@ -1,7 +0,0 @@
[Unit]
Description=API Server socket
[Socket]
ListenStream=10080
NoDelay=true

View File

@ -12,6 +12,9 @@ func init() {
ErrLoadingEnvs = godotenv.Load()
}
func init() {
}
func GetEnv(name, defVal string) string {
env := os.Getenv(name)
if env == "" {

View File

@ -0,0 +1,16 @@
package definition
import "git.pbiernat.dev/golang/rest-api-prototype/internal/app/entity"
type CreateArticleRequest struct {
CategoryID int `json:"category_id"`
Title string `json:"title"`
Intro string `json:"intro"`
Text string `json:"text"`
}
type CreateArticleResponse struct {
Status string `json:"status"`
Data *entity.Article `json:"data"`
Err string `json:"err,omitempty"`
}

View File

@ -0,0 +1,27 @@
package definition
import (
"git.pbiernat.dev/golang/rest-api-prototype/internal/app/entity"
validation "github.com/go-ozzo/ozzo-validation"
)
type CreateCategoryRequest struct {
Name string `json:"name"`
}
func (c CreateCategoryRequest) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.Name, validation.Required, validation.Length(3, 255)),
)
}
type CreateCategoryResponse struct {
Data *entity.Category `json:"data"`
Err string `json:"err,omitempty"` // FIXME: omitempty on/off?
}
type DeleteCategoryRequest struct {
}
type DeleteCategoryResponse struct {
}

View File

@ -0,0 +1,15 @@
package entity
import (
"time"
)
type Article struct {
ID int `json:"id"`
CategoryID int `json:"category_id"`
Title string `json:"title"`
Intro string `json:"intro"`
Text string `json:"text"`
CreateDate time.Time `json:"create_date"`
ModifyDate time.Time `json:"modify_date"`
}

View File

@ -0,0 +1,18 @@
package entity
import (
"time"
)
type Category struct {
ID int `json:"id"`
Name string `json:"name"`
CreateDate time.Time `json:"create_date"`
ModifyDate time.Time `json:"modify_date"` // FIXME: zero-value issue
}
// func (c Category) Validate() error {
// return validation.ValidateStruct(&c,
// validation.Field(&c.Name, validation.Required, validation.Length(3, 255)),
// )
// }

View File

@ -0,0 +1,34 @@
package handler
import (
"log"
"net/http"
"time"
def "git.pbiernat.dev/golang/rest-api-prototype/internal/app/definition"
"git.pbiernat.dev/golang/rest-api-prototype/internal/app/entity"
)
var CreateArticleHandler *Handler
func init() {
CreateArticleHandler = &Handler{
Handle: CreateArticleHandlerFunc,
Request: &def.CreateArticleRequest{},
Response: &def.CreateArticleResponse{},
}
}
func CreateArticleHandlerFunc(h *Handler, w http.ResponseWriter) (interface{}, int, error) {
var art = h.Request.(*def.CreateArticleRequest)
log.Println(art)
return &entity.Article{
ID: 1,
CategoryID: 1,
Title: "Dummy article",
Intro: "Intro",
Text: "Text",
CreateDate: time.Now(),
}, http.StatusCreated, nil
}

View File

@ -0,0 +1,57 @@
package handler
import (
"log"
"net/http"
"strconv"
"time"
def "git.pbiernat.dev/golang/rest-api-prototype/internal/app/definition"
"git.pbiernat.dev/golang/rest-api-prototype/internal/app/entity"
)
var CreateCategoryHandler *Handler
var DeleteCategoryHandler *Handler
func init() {
CreateCategoryHandler = &Handler{
Handle: CreateCategoryHandlerFunc,
Request: &def.CreateCategoryRequest{},
Response: &def.CreateCategoryResponse{},
}
DeleteCategoryHandler = &Handler{
Handle: DeleteCategoryHandlerFunc,
Request: &def.DeleteCategoryRequest{},
Response: &def.DeleteCategoryResponse{},
}
}
func CreateCategoryHandlerFunc(h *Handler, w http.ResponseWriter) (interface{}, int, error) {
var cat = h.Request.(*def.CreateCategoryRequest)
log.Println("Cat input:", cat)
if err := cat.Validate(); err != nil {
log.Println("Create category validation errors:", err)
return nil, http.StatusUnprocessableEntity, err
}
return &entity.Category{
Name: cat.Name,
CreateDate: time.Now(),
}, http.StatusCreated, nil
}
func DeleteCategoryHandlerFunc(h *Handler, w http.ResponseWriter) (interface{}, int, error) {
var cat = h.Request.(*def.DeleteCategoryRequest)
log.Println(cat)
id, _ := strconv.Atoi(h.Params["id"])
log.Println(h.Params)
if id != 1 {
return nil, http.StatusNotFound, nil
}
return nil, http.StatusNoContent, nil
}

View File

@ -34,11 +34,8 @@ type response struct {
Data interface{}
}
func Init(e *Env, h *Handler) *Handler {
// return &Handler{e, h.Handle, h.Request, h.Response, Set{}}
h.Env = e
return h
func New(e *Env, h *Handler) *Handler {
return &Handler{e, h.Handle, h.Request, h.Response, Set{}}
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@ -71,9 +68,7 @@ func encodeResponse(w http.ResponseWriter, res *response, err error) {
}
w.WriteHeader(res.Status)
if res.Data != nil {
json.NewEncoder(w).Encode(res.Data)
}
json.NewEncoder(w).Encode(res.Data)
}
func encodeError(w http.ResponseWriter, status int, e error) {

View File

@ -1,16 +0,0 @@
package app
import "log"
func Panic(v ...any) {
log.Panicln(Name + ":", v)
}
func Panicf(format string, v ...any) {
log.Panicf(Name + ": " + format, v...)
}
func Panicln(v ...any) {
v = append([]any{Name + ":"}, v...)
log.Panicln(v...)
}

View File

@ -4,6 +4,7 @@ import (
"net/http"
"git.pbiernat.dev/golang/rest-api-prototype/internal/app/handler"
"git.pbiernat.dev/golang/rest-api-prototype/internal/app/service"
"github.com/gorilla/mux"
)
@ -17,10 +18,18 @@ func SetupRouter(env *handler.Env) *mux.Router {
r.Use(LoggingMiddleware)
hc := r.PathPrefix("/health").Subrouter()
hc.Handle("", handler.Init(env, handler.HealthCheckHandler)).Methods(http.MethodGet)
hc.Handle("", handler.New(env, handler.HealthCheckHandler)).Methods(http.MethodGet)
auth := r.PathPrefix("/auth").Subrouter()
auth.Handle("/login", handler.Init(env, handler.AuthLoginHandler)).Methods(http.MethodPost)
auth.Handle("/login", handler.New(env, handler.AuthLoginHandler)).Methods(http.MethodPost)
api := r.PathPrefix("/api").Subrouter()
api.Use(service.AuthService.ValidateUserTokenMiddleware) // only /api/** endpoints use this middleware
api.Handle("/article", handler.New(env, handler.CreateArticleHandler)).Methods(http.MethodPost)
api.Handle("/category", handler.New(env, handler.CreateCategoryHandler)).Methods(http.MethodPost)
api.Handle("/category/{id:[0-9]+}", handler.New(env, handler.DeleteCategoryHandler)).Methods(http.MethodDelete)
return r
}

View File

@ -5,18 +5,13 @@ import (
"encoding/json"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strconv"
"time"
def "git.pbiernat.dev/golang/rest-api-prototype/internal/app/definition"
"git.pbiernat.dev/golang/rest-api-prototype/internal/app/handler"
)
const Name = "REST API Service"
type Server struct {
*http.Server
}
@ -34,20 +29,9 @@ func NewServer(env *handler.Env) *Server {
}
func (s *Server) Start() {
if os.Getenv("LISTEN_PID") == strconv.Itoa(os.Getpid()) {
// systemd run
f := os.NewFile(3, "from systemd")
l, err := net.FileListener(f)
if err != nil {
log.Fatalln(err)
}
log.Println("Server listening on " + l.Addr().String())
s.Serve(l)
} else {
log.Println("Server listening on " + s.Addr)
log.Fatalln(s.ListenAndServe())
log.Println("Server listening on " + s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Println(err)
}
}