// 这是个8020端口服务器 问题是用浏览器能访问,使用ajax访问却访问不了,报错:localhost:8020/sayhello. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"net/http"
"net/url"
)
/**
* @Author: YaoWang
* @DateTime: 2017-04-11 10:09:15
* @Description: 返回信息
*/
func sayHelloName(w http.ResponseWriter, r *http.Request) {
//r.Method 判断是什么请求类型
if r.Method == "GET" {
fmt.Fprintf(w, r.Method+"hello, world 这是get请求!!")
} else {
fmt.Fprintf(w, r.Method+"hello, world 这是其他形式请求!!")
}
//这种方式不能处理get和post请求出现相同参数名的情况
r.ParseForm()
// fmt.Println(r.Form["username"])
//解析传过来的参数
// fmt.Println(r.URL.RawQuery)
queryForm, err := url.ParseQuery(r.URL.RawQuery)
if err == nil && len(queryForm["username"]) > 0 {
fmt.Println(r.Form["username"])
}
//当出现src中含有mysql驱动却还是报错的时候 删除原有包 重新get一下 解决问题go get github.com/go-sql-driver/mysql
db, err := sql.Open("mysql", "beego:123456@/qscrm")
defer db.Close()
if err != nil {
fmt.Println("打开数据库失败!!")
}
row, err := db.Query("select * from user_info")
if err != nil {
fmt.Println("查询数据库失败!!")
} else {
var id int = 0
var user_name string = ""
var user_pwd string = ""
var user_group_id int = 0
var user_group_name string = ""
for row.Next() {
row.Scan(&id, &user_name, &user_pwd, &user_group_id, &user_group_name)
fmt.Println("id:", id, ",name:", user_name, id, ",user_pwd:", user_pwd, "user_group_id:", user_group_id, "user_group_name:", user_group_name)
}
}
}
/**
* @Author: YaoWang
* @DateTime: 2017-04-11 10:05:54
* @Description: 主程序
*/
func main() {
//http接收handle信息 返回信息
http.HandleFunc("/sayhello", sayHelloName)
http.HandleFunc("/login", userLogin)
//监听端口
http.ListenAndServe(":8020", nil)
}
/**
* @Author: YaoWang
* @DateTime: 2017-04-12 14:06:15
* @Description: 用户登录
*/
func userLogin(w http.ResponseWriter, r *http.Request) {
fmt.Println("userLogin========")
//加了头信息 ,既可以访问 跨域请求(解决方法)
w.Header().Add("Access-Control-Allow-Origin", "*")
if r.Method == "GET" {
fmt.Fprintf(w, r.Method+"hello, world 这是get请求!!")
} else {
fmt.Fprintf(w, r.Method+"hello, world 这是其他形式请求!!")
}
}
有疑问加站长微信联系(非本文作者)