Skip to content

Instantly share code, notes, and snippets.

@niksteff
Created November 15, 2023 12:25
Show Gist options
  • Save niksteff/c6627654833e37028f763401e8873264 to your computer and use it in GitHub Desktop.
Save niksteff/c6627654833e37028f763401e8873264 to your computer and use it in GitHub Desktop.
Example http handler with api client dep
type APIClient struct {
baseUrl url.URL
}
type Something struct {
Id string // the response data
}
// NewAPIClient is a constructor and instantiating our api
// client once. See you can use url.URL to handle urls which
// has a lot of positive side effects.
func NewAPIClient(baseUrl url.URL) APIClient {
return APIClient{baseUrl: baseUrl}
}
func (c *APIClient) Get(id string) (Something, error) {
// TBD API call to your external service and return the result you want
return Something{}, nil
}
type WebHandler struct{ apiClient APIClient }
// NewWebHandler is a constructor instantiating our http handler
// implementation and accepting our api client dependency
func NewWebHandler(apiClient APIClient) WebHandler {
return WebHandler{apiClient: apiClient}
}
func (h *WebHandler) GetWrapper(w http.ResponseWriter, r *http.Request) {
// TBD get id from request or whatever, we define it here for simplicity
id := "123"
// TBD call api client
res, err := h.apiClient.Get(id)
if err != nil {
// TBD handle error
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error())) // something like this
}
//TBD transform your data
// write response
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(res.Id)) // do not forget to check write errs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment