Now we need to create the Go endpoint.
Open routes.go. Routes are defined in the Routes
function, of the form {version, method, path, handler}
. Notice the path can contain variables, of the form /{var}/
. These variables will be made available to your handler.
The first step is to create your handler. For an example, look at monitoringHandler
in monitoring.go
. Your handler arguments can be any data available to the router (the config and database, or what you can create from them). Passing the db
or prepared Stmt
s is common. The handler function must return a RegexHandlerFunc
. In general, you want to return an inline function, return func(w http.ResponseWriter, r *http.Request, p ParamMap) {...
.
The ResponseWriter
and Request
are standard Go HandlerFunc
parameters. The ParamMap
is a map[string]string
, containing the variables from your route path.
Now, your handler just needs to load the data, format it, and write it to the ResponseWriter
, like any other Go HandlerFunc
.
This is the hard part, where you have to recreate the Perl response. But it‘s all standard Go programming, reading from a database, creating JSON, and writing to the http.ResponseWriter
. If you’re just learning Go, look at some of the other endpoints like monitoring.go
, and maybe google some Golang tutorials on SQL, JSON, and HTTP. The Go documentation is also helpful, particularly https://golang.org/pkg/database/sql/ and https://golang.org/pkg/encoding/json/.
Your handler should be in its own file, where you can create any structs and helper functions you need.
Back to routes.go
, you need to add your handler to the Routes
function. For example, /api/1.2/cdns
would look like {1.2, http.MethodGet, "cdns", wrapHeaders(wrapAuth(cdnsHandler(d.DB), d.Insecure, d.TOSecret, rd.PrivLevelStmt, CdnsPrivLevel))},
.
The only thing we haven‘t talked about are those wrap
functions. They each take a RegexHandlerFunc
and return a RegexHandlerFunc
, which lets them ‘wrap’ your handler. You almost certainly need both of them; if you’re not sure, ask on the mailing list or Slack. You'll notice the wrapAuth
function also takes config parameters, as well as a PrivLevel
. You should create a constant in your handler file of the form EndpointPrivLevel
and pass that. If your endpoint modifies data, use PrivLevelOperations
, otherwise PrivLevelReadOnly
.
That‘s it! Test your endpoint, read Contributing.md if you haven’t, and submit a pull request!
If you have any trouble, or suggestions for this guide, hit us up on the mailing list or Slack.