Path: blob/dev/pkg/js/libs/mysql/mysql_private.go
2070 views
package mysql12import (3"database/sql"4"fmt"5"net"6"net/url"7"strings"8)910type (11// MySQLOptions defines the data source name (DSN) options required to connect to a MySQL database.12// along with other options like Timeout etc13// @example14// ```javascript15// const mysql = require('nuclei/mysql');16// const options = new mysql.MySQLOptions();17// options.Host = 'acme.com';18// options.Port = 3306;19// ```20MySQLOptions struct {21Host string // Host is the host name or IP address of the MySQL server.22Port int // Port is the port number on which the MySQL server is listening.23Protocol string // Protocol is the protocol used to connect to the MySQL server (ex: "tcp").24Username string // Username is the user name used to authenticate with the MySQL server.25Password string // Password is the password used to authenticate with the MySQL server.26DbName string // DbName is the name of the database to connect to on the MySQL server.27RawQuery string // QueryStr is the query string to append to the DSN (ex: "?tls=skip-verify").28Timeout int // Timeout is the timeout in seconds for the connection to the MySQL server.29}30)3132// BuildDSN builds a MySQL data source name (DSN) from the given options.33// @example34// ```javascript35// const mysql = require('nuclei/mysql');36// const options = new mysql.MySQLOptions();37// options.Host = 'acme.com';38// options.Port = 3306;39// const dsn = mysql.BuildDSN(options);40// ```41func BuildDSN(opts MySQLOptions) (string, error) {42if opts.Host == "" || opts.Port <= 0 {43return "", fmt.Errorf("invalid host or port")44}45if opts.Protocol == "" {46opts.Protocol = "tcp"47}48// We're going to use a custom dialer when creating MySQL connections, so if we've been49// given "tcp" as the protocol, then quietly switch it to "nucleitcp", which we have50// already registered.51if opts.Protocol == "tcp" {52opts.Protocol = "nucleitcp"53}54if opts.DbName == "" {55opts.DbName = "/"56} else {57opts.DbName = "/" + opts.DbName58}59target := net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port))60var dsn strings.Builder61dsn.WriteString(fmt.Sprintf("%v:%v", url.QueryEscape(opts.Username), opts.Password))62dsn.WriteString("@")63dsn.WriteString(fmt.Sprintf("%v(%v)", opts.Protocol, target))64if opts.DbName != "" {65dsn.WriteString(opts.DbName)66}67if opts.RawQuery != "" {68dsn.WriteString(opts.RawQuery)69}70return dsn.String(), nil71}7273// @memo74func connectWithDSN(dsn string) (bool, error) {75db, err := sql.Open("mysql", dsn)76if err != nil {77return false, err78}79defer func() {80_ = db.Close()81}()82db.SetMaxOpenConns(1)83db.SetMaxIdleConns(0)8485_, err = db.Exec("select 1")86if err != nil {87return false, err88}89return true, nil90}919293