Skip to content

Instantly share code, notes, and snippets.

@pablodz
Created January 11, 2023 03:38
Show Gist options
  • Save pablodz/816219d766150f9a9ad1ae6f5867faf5 to your computer and use it in GitHub Desktop.
Save pablodz/816219d766150f9a9ad1ae6f5867faf5 to your computer and use it in GitHub Desktop.
Example multitenant microservice written in golang
package main
import (
"fmt"
"net/http"
)
// Tenant struct to hold tenant information
type Tenant struct {
ID int
Name string
IsActive bool
Configuration map[string]string
}
//Tenants map to hold all the tenants
var Tenants = map[int]Tenant{
1: {1, "Tenant 1", true, map[string]string{"config1": "value1"}},
2: {2, "Tenant 2", true, map[string]string{"config1": "value2"}},
}
// GetTenantConfg retrieves the config for a tenant
func GetTenantConfg(tenant int) (Tenant, error) {
if t, ok := Tenants[tenant]; ok {
return t, nil
}
return Tenant{}, fmt.Errorf("Tenant not found")
}
func handler(w http.ResponseWriter, r *http.Request) {
tenant := r.Header.Get("tenant")
if tenant == "" {
http.Error(w, "Tenant header is missing", http.StatusBadRequest)
return
}
// get tenant configuration
t, err := GetTenantConfg(tenant)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Hello from tenant: %s with config: %v", t.Name, t.Configuration)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment