Skip to content

Instantly share code, notes, and snippets.

@sempr
Created February 3, 2020 13:47
Show Gist options
  • Save sempr/344c0f4d1fe924559fc7dd9495d3b4a1 to your computer and use it in GitHub Desktop.
Save sempr/344c0f4d1fe924559fc7dd9495d3b4a1 to your computer and use it in GitHub Desktop.
Composition Instead of Inheritance, golang
package main
import (
"path"
"github.com/gin-gonic/gin"
)
type oauthApp struct {
Prefix string
APIKey string
APISecret string
}
func (a *oauthApp) key(c *gin.Context) {
c.JSON(200, gin.H{"prefix": a.Prefix, "apikey": a.APIKey})
}
func (a *oauthApp) sec(c *gin.Context) {
c.JSON(200, gin.H{"prefix": a.Prefix, "apisec": a.APISecret})
}
func (a *oauthApp) reg(r *gin.Engine){
r.GET(path.Join(a.Prefix, "/key"), a.key)
r.GET(path.Join(a.Prefix, "/sec"), a.sec)
}
type newApp struct{
*oauthApp
Value string
}
func (a *newApp) value(c *gin.Context) {
c.JSON(200, gin.H{"prefix": a.Prefix, "value": a.Value})
}
func (a *newApp) reg(r *gin.Engine) {
a.oauthApp.reg(r)
r.GET(path.Join(a.Prefix, "/value"), a.value)
}
type oldApp struct{
*oauthApp
Value2 string
}
func (a *oldApp) value(c *gin.Context) {
c.JSON(200, gin.H{"prefix": a.Prefix, "value": a.Value2})
}
func (a *oldApp) reg(r *gin.Engine) {
a.oauthApp.reg(r)
r.GET(path.Join(a.Prefix, "/value2"), a.value)
}
func main(){
r := gin.Default()
app1 := newApp{
oauthApp:&oauthApp{
Prefix: "/app1",
APIKey: "apikey1",
APISecret: "apisecret1",
},
Value: "value1",
}
app2 := oldApp{
oauthApp:&oauthApp{
Prefix: "/app2",
APIKey: "apikey2",
APISecret: "apisecret2",
},
Value2: "value2",
}
app1.reg(r)
app2.reg(r)
r.Run(":4000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment