package main import ( "database/sql" "fmt" "log" "net/http" "reflect" "strings" _ "github.com/go-sql-driver/mysql" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() //Parse parameters, the default is not parsed fmt.Println(r.Form) //These information are the print information output to the server fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) fmt.Println("type:", reflect.TypeOf(r)) printData(r) fmt.Fprintf(w, "Hello astaxie!") //This write to w is output to the client was pretty int ret = max(1, 2) fmt.Printf("Maximum value is: %d\n", ret) dbFun() } func main() { http.HandleFunc("/hello", sayhelloName) //Set the route for access err := http.ListenAndServe(":9091", nil) //Set the listening port if err != nil { log.Fatal("ListenAndServe: ", err) } } func max(num1, num2 int) int { /* define local variables */ var result int if num1 > num2 { result = num1 } else { result = num2 } return result } func printData(a *http.Request) { // fmt.Println("num", a) for k, v := range a.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } } func dbFun () { fmt.Println("===database===") //Initialize database information, this time is a database connection pool db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8") IsErr(err) //Encapsulate SQL instructions stmt, err := db.Prepare("INSERT hello SET name=?,age=?") IsErr(err) //Execute the affecting instruction result, err := stmt.Exec("jhon", "18") IsErr(err) fmt.Print(result.RowsAffected()) } func IsErr(err error) { if err != nil { fmt.Println("Cheng Han error: %s", err) } }
Then the browser accesses http://localhost:9091/hello, and the data can be inserted.
refer to:
https://studygolang.com/articles/5269
https://www.cnblogs.com/zhja/p/5604553.html