Skip to content

Instantly share code, notes, and snippets.

View chris001177's full-sized avatar

Chris chris001177

  • india
View GitHub Profile
package main
import (
"net/http"
"time"
)
// As noted above, since we plan to only have one instance
// for those 3 services, we'll declare a singleton instance,
// and make sure we only use them to access those services.
package main
// We use interfaces as the types of our database instances
// to make it possible to write tests and use mock implementations.
type userDB interface {
userRoleByID(id string) string
}
// Note the naming `someConfigDB`. In actual cases we use
// some DB implementation and name our structs accordingly.
package main
import (
"fmt"
"net/http"
"strings"
)
func UserPermissionsByID(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query()["id"][0]
package main
// Note how the main package is the only one importing
// packages other than the definition package.
import (
"github.com/myproject/config"
"github.com/myproject/database"
"github.com/myproject/definition"
"github.com/myproject/handler"
"net/http"
package definition
// Note that in this approach both the singleton instance
// and its interface type are declared in the definition
// package. Make sure this package does not contain any
// logic, otherwise it might need to import other packages
// and its neutral nature is compromised.
var (
UserDBInstance UserDB
ConfigDBInstance ConfigDB
package definition
var RolePermissions map[string][]string
package database
type SomeUserDB struct{}
func (db *SomeUserDB) UserRoleByID(id string) string {
// implementation
}
package database
type SomeConfigDB struct{}
func (db *SomeConfigDB) AllPermissions() map[string][]string {
// implementation
}
package config
import (
"github.com/myproject/definition"
"time"
)
// Since the definition package must not contain any logic,
// managing configuration is implemented in a config package.
func InitPermissions() {
package handler
import (
"fmt"
"github.com/myproject/definition"
"net/http"
"strings"
)
func UserPermissionsByID(w http.ResponseWriter, r *http.Request) {