github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/internal/datasource/masterslave/slaves/dns/mysql/dsn.go (about) 1 // Copyright 2021 ecodeclub 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package mysql 16 17 import ( 18 "strings" 19 20 "github.com/ecodeclub/eorm/internal/errs" 21 22 "github.com/go-sql-driver/mysql" 23 ) 24 25 type Dsn struct { 26 cfg *mysql.Config 27 domain string 28 port string 29 } 30 31 // Init 初始化 32 func (m *Dsn) Init(dsn string) error { 33 cfg, err := mysql.ParseDSN(dsn) 34 if err != nil { 35 return err 36 } 37 index := strings.Index(cfg.Addr, ":") 38 if index == -1 { 39 return errs.NewInvalidDSNError(dsn) 40 } 41 m.domain = cfg.Addr[:index] 42 m.port = cfg.Addr[index+1:] 43 m.cfg = cfg 44 return nil 45 } 46 47 func (m *Dsn) Domain() string { 48 return m.domain 49 } 50 51 // FormatByIp 功能是利用目标 IP 拼接成一个 dsn 52 func (m *Dsn) FormatByIp(ip string) (string, error) { 53 m.cfg.Addr = ip + ":" + m.port 54 return m.cfg.FormatDSN(), nil 55 }