Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Created January 9, 2023 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanmhlv/ffd1420bee7a2b1be931ec207b6a0d1a to your computer and use it in GitHub Desktop.
Save yanmhlv/ffd1420bee7a2b1be931ec207b6a0d1a to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func handleResponse[T any](resp *http.Response, err error, t *T) error {
if err != nil {
return err
}
if resp == nil {
return fmt.Errorf("response is nil")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(t)
}
func handleRequest[T any](req *http.Request, t *T) error {
if req == nil {
return fmt.Errorf("request is nil")
}
defer req.Body.Close()
return json.NewDecoder(req.Body).Decode(t)
}
func main() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment