Created
January 11, 2023 03:38
-
-
Save pablodz/816219d766150f9a9ad1ae6f5867faf5 to your computer and use it in GitHub Desktop.
Example multitenant microservice written in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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