Untitled

 avatar
unknown
golang
4 years ago
1.6 kB
10
Indexable
package main

import (
	"context"
	"flag"
	"fmt"

	"net/http"
	"net/http/pprof"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

func connect_server(url string) {
	fmt.Println(url)
	clientOptions := options.Client().ApplyURI(url)
	ctx, _ := context.WithTimeout(context.Background(), 32*time.Second)
	conn, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		fmt.Printf("new %s mongo connection error: %v\n", url, err)
		return
	} else {
		fmt.Println("connection is created")
	}
	defer conn.Disconnect(ctx)

	err = conn.Ping(ctx, readpref.Primary())
	if err != nil {
		fmt.Printf("ping %s ping error: %v\n", url, err)
		return
	}
	return
}

func hiHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hi"))
}

func main() {

	mongo_url := flag.String("mongo_url", "mongodb://localhost:27017/admin", "mogodb url")
	workers := flag.Int("workers", 1, "num of parallel workers")

	flag.Parse()

	r := http.NewServeMux()
	r.HandleFunc("/", hiHandler)

	// Регистрация pprof-обработчиков
	r.HandleFunc("/debug/pprof/", pprof.Index)
	r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	r.HandleFunc("/debug/pprof/profile", pprof.Profile)
	r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	r.HandleFunc("/debug/pprof/trace", pprof.Trace)

	go func() {
		http.ListenAndServe(":8080", r)
	}()

	var waitgroup sync.WaitGroup

	for {
		for i := 1; i <= *workers; i++ {
			waitgroup.Add(1)
			go func() {
				connect_server(*mongo_url)
				waitgroup.Done()
			}()
		}
		waitgroup.Wait()
		fmt.Println("Done!")
	}
}
Editor is loading...