8000 GitHub - agc11/gowait: async/await for golang · GitHub
[go: up one dir, main page]

Skip to content
agc11Public

About

async/await for golang

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

Async/Await for golang

coverage-lines

example usage

package main

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/agc11/gowait"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func main() {

	type apiResponse struct {
		Id        int    `json:"id"`
		FirstName string `json:"firstName"`
		LastName  string `json:"lastName"`
		FullName  string `json:"fullName"`
		Title     string `json:"title"`
		Family    string `json:"family"`
		Image     string `json:"image"`
		ImageUrl  string `json:"imageUrl"`
	}

	requestApi := func(ctx context.Context) (apiResponse, error) {
		resp, err := http.Get("https://thronesapi.com/api/v2/Characters/0")

		if err != nil {
			return apiResponse{}, errors.New("error request")
		}
		body, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			return apiResponse{}, errors.New("error ioutil.ReadAll")
		}

		var res apiResponse
		err = json.Unmarshal(body, &res)

		if err != nil {
			return apiResponse{}, errors.New("error Unmarshal")
		}

		return res, nil
	}

	ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	future := gowait.NewFuture(context.Background(), requestApi)
	result := future.Await(ctxTimeout)

	if result.Error != nil {
		log.Fatalln(result.Error)
	}

	log.Printf("%#v\n", result.Value)
}

About

async/await for golang

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0