Go Programming Language Tutorial (Part 5)
Go Programming Language Tutorial (Part 5)
This tutorial focuses on building and deploying microservices in Go, integrating middleware,
interacting with cloud services, and ensuring security in Go applications.
1. Building a Microservice
Microservice Basics
A microservice is a standalone, independently deployable service that focuses on a specific
functionality.
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
// Add a user
func addUser(w http.ResponseWriter, r *http.Request) {
var user User
json.NewDecoder(r.Body).Decode(&user)
users = append(users, user)
json.NewEncoder(w).Encode(user)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/users", getUsers).Methods("GET")
r.HandleFunc("/users", addUser).Methods("POST")
http.ListenAndServe(":8080", r)
}
Run the service and test it with tools like curl or Postman.
2. Middleware in Go
Middleware is a function that wraps HTTP handlers to perform tasks like logging, authentication, or
rate limiting.
import (
"log"
"net/http"
"time"
)
func main() {
http.Handle("/", loggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter,
r *http.Request) {
w.Write([]byte("Hello, Middleware!"))
})))
http.ListenAndServe(":8080", nil)
}
3. Service-to-Service Communication
RESTful Communication
Use Go’s net/http package to call other services.
func main() {
users, err := fetchUsers()
if err != nil {
fmt.Println("Error fetching users:", err)
return
}
4. Cloud Integration
AWS SDK Integration
Install the AWS SDK for Go:
bash
Copy code
go get github.com/aws/aws-sdk-go
Example: Upload to S3
go
Copy code
package main
import (
"bytes"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
svc := s3.New(sess)
bucket := "your-bucket-name"
key := "example.txt"
body := bytes.NewReader([]byte("Hello, S3!"))
_, err := svc.PutObject(&s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
Body: body,
})
return err
}
func main() {
if err := uploadToS3(); err != nil {
fmt.Println("Failed to upload:", err)
} else {
fmt.Println("Upload successful!")
}
}
import (
"fmt"
"os"
)
func main() {
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
fmt.Println("API_KEY is not set")
} else {
fmt.Println("API_KEY:", apiKey)
}
}
Input Validation
Always validate user inputs to prevent injection attacks.
import (
"net/http"
"regexp"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func main() {
config := api.DefaultConfig()
client, err := api.NewClient(config)
if err != nil {
log.Fatal(err)
}
registration := &api.AgentServiceRegistration{
ID: "user-service",
Name: "user-service",
Address: "localhost",
Port: 8080,
}
7. Observability
Distributed Tracing with Jaeger
Install Jaeger’s client library:
bash
Copy code
go get github.com/uber/jaeger-client-go
import (
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
"log"
)
func main() {
cfg := config.Configuration{
ServiceName: "my-service",
Sampler: &config.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
LocalAgentHostPort: "localhost:6831",
},
}
opentracing.SetGlobalTracer(tracer)
span := tracer.StartSpan("my-operation")
span.Finish()
log.Println("Tracing example completed")
}
8. Deploying Go Microservices
Using Kubernetes
Deploy your microservice using Kubernetes.
Deployment YAML
yaml
Copy code
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
spec:
replicas: 2
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
spec:
containers:
- name: user-service
image: myuser-service-image:latest
ports:
- containerPort: 8080