To learn how to build web-app in Go, I have created small web app where I am using Gorilla mux and I have mainly below packages main, handlers, model, structs.
I want to use goroutines while going through documentation I came to know that I need to use sync package along with go fun(). I tried to use as shown below, within the same package and it is working fine. But how to sync goroutine if called function are from diffrent package?
// same package : working
package models
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func Func1() (string, error) {
lexpiry := ReadDatafrom()
wg.Add(1)
go validExp(string(lexpiry))
----
----
wg.Wait()
----
return "S/F", err
}
func validExp(lexpiry string) {
fmt.Println("CHeck Expiry Date")
wg.Done()
}
But if I need to call a function of different package, of course I can add go keyword before package like: go otherPackage.Function()
But how will I sync it? I mean the function which we are calling with go must have wg.Done()?
// Diffrent package : ? ( need guidance how to achive this )
package handlers
import (
"fmt"
"sync"
"go_mjolnir/models"
"net/http"
)
var wg sync.WaitGroup
func Func1(w http.ResponseWriter, r *http.Request) {
lexpiry := ReadDatafrom()
wg.Add(1)
go models.ValidExp(string(lexpiry))
----
calling func of model package
----
wg.Wait()
----
// return json response
}
package model
---
---
func validExp(lexpiry string) {
fmt.Println("CHeck Expiry Date")
// wg.Done()
// how to call wg.Done() of handllers packge , is it right way ?
}
can some one guide me on this? How to sync goroutine if called function are from different packages?