Konténerizált API
This commit is contained in:
9
Dockerfile
Normal file
9
Dockerfile
Normal file
@@ -0,0 +1,9 @@
|
||||
FROM golang:1.23-alpine
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
RUN go build -o go-api main.go
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["./go-api"]
|
||||
8
docker-compose.yml
Normal file
8
docker-compose.yml
Normal file
@@ -0,0 +1,8 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
go-api:
|
||||
build: .
|
||||
container_name: go-api
|
||||
ports:
|
||||
- "8080:8080"
|
||||
54
main.go
Normal file
54
main.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type AddRequest struct {
|
||||
PinCode int `json:"pinCode"`
|
||||
N1 int `json:"n1"`
|
||||
N2 int `json:"n2"`
|
||||
}
|
||||
|
||||
type AddResponse struct {
|
||||
Output int `json:"output"`
|
||||
}
|
||||
|
||||
func healthHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(HealthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func addHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var req AddRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid json", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.PinCode != 1234 {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
result := req.N1 + req.N2
|
||||
resp := AddResponse{Output: result}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/health", healthHandler)
|
||||
http.HandleFunc("/add", addHandler)
|
||||
|
||||
fmt.Println("Server running on port 8080...")
|
||||
http.ListenAndServe(":8080", nil)
|
||||
}
|
||||
Reference in New Issue
Block a user