Dolphin is a simple web framework for Golang.
-
Install dolphin by Go cli tool:
go get -u github.com/ghosind/dolphin
-
Import dolphin in your code:
import "github.com/ghosind/dolphin"
-
The following example shows how to implement a simple web service, and it'll reads parameter name from request query and return the message as a JSON object.
package main import ( "fmt" "github.com/ghosind/dolphin" ) func handler(ctx *dolphin.Context) { name := ctx.Query("name") ctx.JSON(ctx.O{ "message": fmt.Sprintf("Hello, %s", name), }) } func main() { app := dolphin.Default() app.Use(handler) app.Run() }
-
Save the above code as
app.go
and run it with the following command:go run app.go # Server running at :8080.
-
Visit
http://locahost:8080?name=dolphin
by your browser or other tools to see the result.
func handler(ctx *dolphin.Context) {
firstName := ctx.Query("firstName")
lastName := ctx.QueryDefault("lastName", "Doe")
ctx.JSON(ctx.O{
"message": fmt.Sprintf("Hello, %s ", firstName, lastName),
})
}
type Payload struct {
Name string `json:"name"`
}
func handler(ctx *dolphin.Context) {
var payload Payload
if err := ctx.PostJSON(&payload); err != nil {
// Return 400 Bad Request
ctx.Fail(ctx.O{
"message": "Invalid payload",
})
return
}
ctx.JSON(ctx.O{
"message": fmt.Sprintf("Hello, %s ", payload.Name),
})
}
func CustomMiddleware() {
// Do something
return func (ctx *dolphin.Context) {
// Do something before following handlers
ctx.Next()
// Do something after following handlers
}
}
func main() {
app := dolphin.Default()
app.Use(CustomMiddleware())
// ...
}
Distributed under the MIT License. See LICENSE file for more information.