Skip to content

Instantly share code, notes, and snippets.

@jphastings
Created July 6, 2018 09:15
Show Gist options
  • Save jphastings/287c5b9721c7ef73839efa0eb508ccba to your computer and use it in GitHub Desktop.
Save jphastings/287c5b9721c7ef73839efa0eb508ccba to your computer and use it in GitHub Desktop.
Structuring a gin webapplication: an idea
package main
import (
"fmt"
"github.com/go-gonic/gin"
)
var Routes struct {
Homepage func() string
CreateWidget func() string
UpdateWidget func(string) string
}
func init() {
Routes.Homepage = func() string {
return "/"
}
Routes.CreateWidget = func() string {
return "/api/widgets"
}
Routes.UpdateWidget = func(widgetId string) {
return fmt.Sprintf("/api/widgets/%s", widgetId)
}
}
func main() {
endpoints = &ApplicationDependencies{}
router := gin.Default()
router.GET(Routes.Homepage(), endpoints.Homepage)
router.POST(Routes.CeateWidget(), endpoints.CreateWidget)
router.PUT(Routes.UpdateWidget(":id"), endpoints.UpdateWidget)
router.Run()
}
type ApplicationDependencies struct {
// New Relic
// Datadog
}
func (deps *ApplicationDependencies) Homepage(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"createEndpointPath": Routes.CreateWidget(),
// If the clientside needs the URL template in a particular structure that can be achieved here
"updateEndpointpath": Routes.UpdateWidget("%%id%%"),
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment