I am new to Golang programming and was wondering if this is possible in golang.
- I create an SDK in golang that exposes an API (/golang-sdk/test-api POST)
- Some Project adds my SDK as dependency
- The API (/golang-sdk/test-api) gets exposed from the service.
Thanks in Advance!!
P.S: If it is possible, any POC or document doing the same would be really helpful.
CodePudding user response:
Welcome, you will like go :)
There are two approaches I can come up with:
Have a package with the handlers, and then handle them where you do the import. This way it will be clear what endpoints handle at the place where you do the import. You will have more control this way and imo it will be easier to maintain.
In your package with the rest API, have a method that setups the server with the handlers. You can probably do that in the init of the package with the API, so whenever it is imported
import _ "your_rest_package"
it will just start, it will start the server - this is shady and probably harder to maintain. Or have a method that starts your API and use it in the packages depending on it. It will look neath, but still I would not prefer this.
CodePudding user response:
Yes, this is possible. All you have to do is register your HTTP handler in (one of) the init functions for your package:
package sdk
import (
"net/http"
)
func init() {
http.HandleFunc("/golang-sdk/test-api", TestHandler)
}
func TestHandler(w http.ResponseWriter, r *http.Request) {
// ...
}
As long as the user of your package uses the DefaultServeMux, your handler is automatically available by just importing your package:
package main
import (
"log"
"net/http"
_ "your/sdk"
)
func main() {
log.Fatal(http.ListenAndServe(":3000", nil))
}
Your HTTP handler is exported, so it can be used with any other ServeMux or third-party router, registered under an alternative path, wrapped with authentication, etc., etc.
This is precisely how the net/http/pprof package in the standard library works. Take a look, it's small.
It also shows another good practice: create a separate package for the HTTP handler. Just importing runtime/pprof does not register the HTTP handler. There's a separate package for that and only that. Exposing any kind of functionality to the outside should always be a conscious decision, never an accident.