slimhttp
1.0.0
Slimhttp是一个简单的API库,用于快速,轻松地编写JSON/XML服务。它的编写目的是提供诸如服务定义(Slimhttp.endpoint)之类的套件,同时避免所有额外的RPC逻辑和编码器/解码器接口。该项目的目的是实施与编写API服务相关的许多基本样板,以便您专注于编写业务逻辑。
Slimhttp的核心是端点类型。从现在开始的所有端点将采用以下功能签名的形式。
type Endpoint func(*http.Request) (interface{}, error)
http.handlerfunc的使用是撰写此库的推动力。满足http.handlerfunc类型(包括所有编码和在同一功能中检查的所有编码)不是我喜欢的东西,因此提出了上述类型,以使事情变得更加简单。现在使用上面的新端点类型可以使您能够卸载所有编码和错误处理到此库的能力,从而使实施业务逻辑的过程变得更加清洁。
这只是该项目的开始。我知道这是非常基本的,这就是重点。如果您真正希望看到的是您在API逻辑中正常使用的实现,我很想听听它! - 发布问题或抽屉重新要求。
package main
import (
"errors"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/s32x/slimhttp"
)
func main () {
r := slimhttp . NewRouter () // Create a new router
r . HandleJSONEndpoint ( "/hello/{name}/" , Hello ) // Bind an Endpoint to the router at the specified path
log . Fatal ( r . ListenAndServe ( 8080 )) // Start the service!
}
// HelloResponse is an example response struct that will be
// encoded to JSON on a Hello request
type HelloResponse struct {
Message string `json:"message"`
Success bool `json:"success"`
}
// Hello is an example Endpoint method. It receives a request
// so that you have access to everything on the request and
// returns a successful body or error
func Hello ( r * http. Request ) ( interface {}, error ) {
name := mux . Vars ( r )[ "name" ] // The name passed on the request
switch name {
case "basic-error" :
// An example of returning a raw error
err := errors . New ( "This is a basic error" )
return nil , err
case "standard-error" :
// An example of returning a predefined Error
return nil , slimhttp . ErrorBadRequest
case "fancy-error" :
// An example of returning a fully self-defined Error
err := errors . New ( "This is a fancy error" )
return nil , slimhttp . NewError ( "This is a fancy error!" , http . StatusBadRequest , err )
}
// All other names will be returned on a HelloResponse
return & HelloResponse {
Message : fmt . Sprintf ( "Hello %s!" , name ),
Success : true ,
}, nil
}
版权所有©2022 S32X
特此免费授予任何获得此软件副本和相关文档文件副本(“软件”)的人,以无限制处理该软件,包括无限制,使用,复制,修改,合并的权利,发布,分发,分布和/或出售该软件的副本,并允许提供该软件的人,但要遵守以下条件:
上述版权通知和此许可通知应包含在软件的所有副本或大量部分中。
该软件是“按原样”提供的,没有任何形式的明示或暗示保证,包括但不限于适销性,特定目的的适用性和非侵权的保证。在任何情况下,作者或版权持有人均不应对任何索赔,损害赔偿或其他责任责任,无论是在合同,侵权或其他方面的诉讼中,与软件,使用或与该软件或使用或其他交易有关的诉讼或其他责任软件。