Created
July 6, 2018 09:15
-
-
Save jphastings/287c5b9721c7ef73839efa0eb508ccba to your computer and use it in GitHub Desktop.
Structuring a gin webapplication: an idea
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" | |
"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