how can i catch the error with errorgroup? - go

here I want the "run" function in the runner.go package to run continuously by using the "errorgroup". How can I catch this error later when it receives an error? Below is a sample code block that I want to do but fail.
Thank you.
main.go
package main
import (
"context"
"fmt"
"awesomeProject/runner"
"golang.org/x/sync/errgroup"
"time"
)
func main() {
ctx := context.Background()
g, ctx := errgroup.WithContext(ctx)
g.Go(func() (err error) {
return runner.Start(ctx, 1 * time.Second)
})
if err := g.Wait(); err != nil {
fmt.Println(err)
fmt.Println("app terminated")
}
}
runner.go
package runner
import (
"context"
"errors"
"fmt"
"time"
)
func Start(ctx context.Context, dur time.Duration) error {
ticker := time.NewTicker(dur)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
run(ctx)
}
}
}
func run(ctx context.Context) error {
fmt.Println(time.Now().String())
return errors.New("run:error")
}

Related

go build doesn't recognise methods

I try to setup a small Golang Microservice for users with Gin and Mongodb.
package main
import (
"context"
"fmt"
"github.com/wzslr321/artiver/entity"
"github.com/wzslr321/artiver/settings"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"os"
"os/signal"
"syscall"
"time"
)
type application struct {
users *entity.UserCollection
}
var app *application
func init() {
initMongo()
}
func initMongo() {
oc := options.Client().ApplyURI(settings.MongodbSettings.Uri)
client, err := mongo.NewClient(oc)
if err != nil {
log.Fatalf("Error occured while initializing a new mongo client: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatalf("Errorr occurred while connecting to a client: %v", err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
log.Println("Successfully connected to the database!")
app = &application{
users: &entity.UserCollection{
C: client.Database("artiver").Collection("users"),
},
}
}
func main() {
router := app.InitRouter()
It doesn't show any errors in my IDE ( GoLand ), but when I try to build it I get an error:
# command-line-arguments
users/cmd/app/main.go:67:15: app.InitRouter undefined (type *application has no field or method InitRouter)
It it easily visible on the image above, that I do have access to such a method. It is defined in the same package.
package main
import (
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
"net/http"
)
func (app *application) InitRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Recovery())
r.Use(cors.Default())
r.GET("/", func(ctx *gin.Context) {
ctx.String(http.StatusOK, "Hello World")
})
user := r.Group("/api/user")
{
user.POST("/add", app.CreateUser)
}
return r
}
I have no idea how am I supposed to fix it and what is done wrong. I'd appreciate any hint about what isn't done correctly.
Answer based on #mkopriva help in comments.
The issue was related to not running all needed .go files.
In my case, the solution was to build it this way in my Makefile:
go build -o $(path)users cmd/app/*
In similar cases, go run . most likely will do the job.

GORM DB Connection on other package

I start learning Go, reading about pointers, and want to split my database connection , and handler function for API. Already tried myself, by following this solution , but when i trying to read data, i am having this error
[2018-06-26 21:59:45] sql: database is closed
this is my source code.
db.go
package db
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"os"
)
var Db *gorm.DB
func Open() error {
var err error
_ = godotenv.Load(".env")
dbType := os.Getenv("DB_TYPE")
dbConnString := os.Getenv("DB_CONN_STRING")
Db, err = gorm.Open(dbType, dbConnString)
if err != nil {
fmt.Println(err)
}
Db.LogMode(true)
defer Db.Close()
return err
}
func Close() error {
return Db.Close()
}
person.go
package model
import (
"github.com/jinzhu/gorm"
"github.com/gin-gonic/gin"
"fmt"
"namastra/gin/result"
"namastra/gin/db"
)
type Person struct {
gorm.Model
FirstName string `json:”firstname”`
LastName string `json:”lastname”`
}
/*var db *gorm.DB
var err error*/
func GetPeople(c *gin.Context) {
var people []result.Person
if err := db.Db.Select("ID,first_name,last_name").Find(&people).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, people)
}
}
main.go
package main
import (
"log"
"namastra/gin/handler"
"namastra/gin/model"
"net/http"
"time"
"github.com/adam-hanna/jwt-auth/jwt"
"github.com/gin-gonic/gin"
_ "github.com/jinzhu/gorm/dialects/postgres"
"namastra/gin/db"
)
func main() {
if err := db.Open(); err != nil {
// handle error
panic(err)
}
defer db.Close()
router := gin.Default()
router.Use(gin.Recovery())
private := router.Group("/auth")
....(ommited)
router.GET("/", gin.WrapH(regularHandler))
router.GET("/people/", model.GetPeople)
router.Run("127.0.0.1:3000")
}
Sorry for my bad english, any kind of help is appreciated.
thank you.
edit1: case closed.
solution is by removing
defer Db.Close()
from db.go.
edi2: update some knowledge i learn by working in go project
As start learning GO, usually we put everything on single main.go file, and we think to split the code to multiple files.
That is the time Dependency Injection comes to play.
we can create something like this Env to store the handler.
type Env struct {
db *sql.DB
logger *log.Logger
templates *template.Template
}
and create something like this in models/db.go
package models
import (
"database/sql"
_ "github.com/lib/pq"
)
func NewDB(dataSourceName string) (*sql.DB, error) {
db, err := sql.Open("postgres", dataSourceName)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
return db, nil
}
main.go files
package main
import (
"namastra/gin/models"
"database/sql"
"fmt"
"log"
"net/http"
)
type Env struct {
db *sql.DB
}
func main() {
db, err := models.NewDB("postgres://user:pass#localhost/bookstore")
if err != nil {
log.Panic(err)
}
env := &Env{db: db}
http.HandleFunc("/peoples", env.peoplesIndex)
http.ListenAndServe(":3000", nil)
}
func (env *Env) peoplesIndex(w http.ResponseWriter, r *http.Request) {
# ...
}
and in models/people.go
package models
import "database/sql"
type Book struct {
Isbn string
Title string
Author string
Price float32
}
func AllPeoples(db *sql.DB) ([]*People, error) {
rows, err := db.Query("SELECT * FROM peoples")
if err != nil {
return nil, err
}
defer rows.Close()
# ... ommited for simplicity
}
you can read the full code & explanation in Alex Edwards post

How to dynamically set a variable in a defer call

Example code:
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("error 1")
defer fmt.Println(err)
err = errors.New("error 2")
}
In this case, I want fmt.Println to print out error 2.
err is already defined when you set the defer so what you what you likely want to do is wrap it in a func like below. Hope this helps.
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("error 1")
defer func() {
fmt.Println(err)
}()
err = errors.New("error 2")
}

Creating http handler

I have main.go and I want changing to better structure(similarly main2.go ) due to if the proyect would grow up, would not be easy interpret for new developers the code.
My idea is create a folder called handle and put in it the file handle.go with all the handles methods, the trouble that I find is that I do not know how to set up http.HandleFunc("/R1", HandlerOne) and http.HandleFunc("/R2", HandlerTwo) in handler.go and call it from main2.go.
main.go
package main
import (
"fmt"
"net/http"
)
func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}
func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}
func main() {
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
main2.go
package main
import (
"fmt"
"net/http"
)
func main() {
// Call handle.go
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
handle.go
package handle
import (
"fmt"
"net/http"
)
func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}
func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}
Note:
Thanks #kluyg for your answer. I going to add that i want that seems I do not explain very well:
That I want is create a function in
handle.go where can I can put all the mapping of the handles. i.e some like that
func SetUpMapping(...){
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)
..... //Others mapping
http.HandleFunc("/RN", HandlerN)
}
where ... should be one refence to http, but this is one package, and in the main something like code 3
code 3
main2.go
package main
import (
"fmt"
"net/http"
"handlers/handle"
)
func main() {
// Call handle.go
handle.SetUpMapping(...) // i dont know what parameter put here
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
I took your code and put main2.go into $GOPATH/handlers folder and handle.go in $GOPATH/handlers/handle folder. Then I changed main2.go to be
package main
import (
"fmt"
"net/http"
"handlers/handle"
)
func main() {
// Call handle.go
http.HandleFunc("/R1", handle.HandlerOne)
http.HandleFunc("/R2", handle.HandlerTwo)
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
It compiles and works fine. I believe this is what you asked for.
UPDATE
OK, you can add this to your handle.go
func SetUpMapping() {
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)
..... //Others mapping
http.HandleFunc("/RN", HandlerN)
}
then in main2.go
package main
import (
"fmt"
"net/http"
"handlers/handle"
)
func main() {
// Call handle.go
handle.SetUpMapping() // you don't need any parameters here
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}

malformed HTTP status code "/" error in Go

Server.go
package main
import (
"fmt"
"net/http"
//"strings"
"encoding/json"
"io/ioutil"
"strconv"
"net"
"bufio"
)
type Message struct {
Text string
}
func Unmarshal(data []byte, v interface{}) error
func main() {
//http.HandleFunc("/", handler)
server,_ := net.Listen("tcp", ":" + strconv.Itoa(8080))
if server == nil {
panic("couldn't start listening: ")
}
conns := clientConns(server)
for {
go handleConn(<-conns)
}
}
func clientConns(listener net.Listener) chan net.Conn {
ch := make(chan net.Conn)
i := 0
go func() {
for {
client, _ := listener.Accept()
if client == nil {
fmt.Printf("couldn't accept: ")
continue
}
i++
fmt.Printf("%d: %v <-> %v\n", i, client.LocalAddr(), client.RemoteAddr())
ch <- client
}
}()
return ch
}
func handleConn(client net.Conn) {
b := bufio.NewReader(client)
fmt.Println("Buffer")
for {
line, err := b.ReadBytes('\n')
if err != nil { // EOF, or worse
break
}
client.Write(line)
}
}
Client.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"flag"
//"io"
// "net"
// "net/rpc"
// "sync"
)
func Unmarshal(data []byte, v interface{}) error
func Marshal(v interface{}) ([]byte, error)
type Message struct {
Text string
}
func main(){
var flagtext = flag.String("flagtext", "Hello!", "Flag")
flag.Parse()
var text string
text = *flagtext
m := Message{text}
var m1 Message
b, err := json.Marshal(m)
if err == nil{
resp, err := http.Post("http://127.0.0.1:8080","application/json", strings.NewReader(string(b)))
if err != nil{
log.Fatal("Error while post: %v",err)
}
fmt.Println(resp)
err = json.Unmarshal(b, &m1)
}
}
Error I get when I run client.go is this:
Error while post: %vmalformed HTTP status code "/"
Though, the server registers a channel for each post, it shows a malformed HTTP status code. Is it because I'm listening in the wrong channel? I'm confused why this error is occurring.
This line in the server code:
client.Write(line)
sends the request line back to the client. Since the client is posting something like GET / HTTP/1.1, this means that the server is responding with something like GET / HTTP/1.1, instead of something like HTTP/1.1 200 OK. The error-message you're seeing is because / appears in the status-code position.
In server.go it seems you are trying to write your own HTTP server from the TCP socket level up. This is unnecessary work - take the easy route and use the built-in HTTP server API.
The general outline of such a server is like this:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
and is described further in this article. More documentation is in net/http.

Resources