diff --git a/serverless/Makefile b/serverless/Makefile new file mode 100644 index 0000000..908f753 --- /dev/null +++ b/serverless/Makefile @@ -0,0 +1,25 @@ +# Copyright 2022 PingCAP, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +.PHONY: all build run + +all: + make build run + +build: + go build -o bin/sql-driver-example + +run: + ./bin/sql-driver-example \ No newline at end of file diff --git a/serverless/go.mod b/serverless/go.mod new file mode 100644 index 0000000..842a695 --- /dev/null +++ b/serverless/go.mod @@ -0,0 +1,5 @@ +module github.com/pingcap-inc/tidb-example-golang/serverless + +go 1.18 + +require github.com/go-sql-driver/mysql v1.6.0 diff --git a/serverless/go.sum b/serverless/go.sum new file mode 100644 index 0000000..20c16d6 --- /dev/null +++ b/serverless/go.sum @@ -0,0 +1,2 @@ +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= diff --git a/serverless/serverless.go b/serverless/serverless.go new file mode 100644 index 0000000..f6cea23 --- /dev/null +++ b/serverless/serverless.go @@ -0,0 +1,43 @@ +package main + +import ( + "crypto/tls" + "database/sql" + "fmt" + "github.com/go-sql-driver/mysql" +) + +const ( + tlsConfigKeyName = "tidb" + host = "{serverless tier host}" + port = 4000 + username = "{serverless tier username}" + password = "{serverless tier password}" +) + +func main() { + mysql.RegisterTLSConfig(tlsConfigKeyName, &tls.Config{ + MinVersion: tls.VersionTLS12, + ServerName: host, + }) + + dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/test?tls=%s", + username, password, host, port, tlsConfigKeyName) + db, err := sql.Open("mysql", dsn) + if err != nil { + panic(err) + } + defer db.Close() + + rows, err := db.Query("SELECT VERSION()") + if err != nil { + panic(err) + } + defer rows.Close() + + for rows.Next() { + version := "" + rows.Scan(&version) + fmt.Println(version) + } +}