An initial structure for building Go web apps.
- Clone this repository in a location from your
GOPATH
- Replace all occurrences of
go-init
with the name of the project
If you wish to change the port that the app will listen to, go to
main.go
- Install the routing package
go get github.com/husobee/vestigo
- Import the
features
package
import f "github.com/[vendor]/[project]/features"
- Routes can be defined in
routes/routes.go
in theRegister
method as follows:
r.Get('/path', Serve(f.DoSomething))
- Install the validation package
go get gopkg.in/go-playground/validator.v9
- Insall the parsing package
go get github.com/gorilla/schema
- Use the following snippet to parse and validate given input as a struct (see here for errors)
type ListingInput struct {
Limit uint `schema:"limit" validate:"min=0,max=100"`
Offset uint `schema:"offset" validate:"min=0"`
}
func ParseListingInput(r *http.Request) *ListingInput {
input := new(ListingInput)
schema.NewDecoder().Decode(input, r.URL.Query())
return input
}
func Validate(input *ListingInput) {
if err := validator.New().Struct(input); err != nil {
panic(throw.InvalidInputError(err.Error(), 1000, 400))
}
}
- Import the
response
package
import "github.com/[vendor]/[project]/response
response.JSON(w, data)
response.JSONError(w, status, errorCode, errorMessage)
- Define errors in the
throw
package atthrow/errors.go
as a struct
type SomethingWrong struct {
*HTTPError
}
- For each error, better have a factory method to help make a new instance of the error, i.e.
func SomethingWrongError(m string, c, s uint16) SomethingWrong {
return InvalidInput{&HTTPError{Message: m, Code: c, Status: s}r}
}