https://github.com/xgfone/go-apiserver
An library to build the API server
https://github.com/xgfone/go-apiserver
api api-gateway api-server apigateway apiserver gateway gateway-api go golang http router server service
Last synced: 11 months ago
JSON representation
An library to build the API server
- Host: GitHub
- URL: https://github.com/xgfone/go-apiserver
- Owner: xgfone
- License: apache-2.0
- Created: 2021-11-21T10:32:54.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-11-22T09:21:59.000Z (over 1 year ago)
- Last Synced: 2024-11-22T10:25:40.322Z (over 1 year ago)
- Topics: api, api-gateway, api-server, apigateway, apiserver, gateway, gateway-api, go, golang, http, router, server, service
- Language: Go
- Homepage:
- Size: 1.22 MB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-apiserver
[](https://github.com/xgfone/go-apiserver/actions/workflows/go.yml)
[](https://pkg.go.dev/github.com/xgfone/go-apiserver)
[](https://raw.githubusercontent.com/xgfone/go-apiserver/master/LICENSE)


The library is used to build an API server.
## Install
```shell
$ go get -u github.com/xgfone/go-apiserver
```
## Example
### Simple HTTP Router
```go
package main
import (
"fmt"
"net/http"
"github.com/xgfone/go-apiserver/http/middleware"
"github.com/xgfone/go-apiserver/http/middleware/context"
"github.com/xgfone/go-apiserver/http/middleware/logger"
"github.com/xgfone/go-apiserver/http/middleware/recover"
"github.com/xgfone/go-apiserver/http/reqresp"
"github.com/xgfone/go-apiserver/http/router"
"github.com/xgfone/go-apiserver/http/router/ruler"
"github.com/xgfone/go-apiserver/http/server"
)
func httpHandler(route string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := reqresp.GetContext(r.Context())
fmt.Fprintf(w, "%s: %s", route, c.Data["id"])
}
}
func main() {
// Build the routes.
routeManager := ruler.NewRouter()
routeManager.Path("/path1/{id}").Method("GET").Handler(httpHandler("route1"))
routeManager.Path("/path2/{id}").GET(httpHandler("route2"))
router := router.NewRouter(routeManager)
router.Use(middleware.MiddlewareFunc(context.Context)) // Use a function as middleware
router.Use(
middleware.New("logger", 1, logger.Logger), // Use the named priority middleware
middleware.New("recover", 2, recover.Recover), // Use the named priority middleware
)
// http.ListenAndServe("127.0.0.1:80", router)
server.Start("127.0.0.1:80", router)
// Open a terminal and run the program:
// $ go run main.go
//
// Open another terminal and run the http client:
// $ curl http://127.0.0.1/path1/123
// route1: 123
// $ curl http://127.0.0.1/path2/123
// route2: 123
}
```