Skip to content

Commit

Permalink
添加前后端分离的接口式webserver
Browse files Browse the repository at this point in the history
  • Loading branch information
tcsecchen committed Apr 26, 2018
1 parent 43bac33 commit 7328867
Show file tree
Hide file tree
Showing 5 changed files with 204 additions and 146 deletions.
7 changes: 4 additions & 3 deletions attention.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
4. go里的自增运算符只有——“后++”,i++为语句,不是表达式,j = i++ 是错的
5. 数组传递的是拷贝,不是引用
6. go 结构体转json时候:结构体必须是大写字母开头的成员才会被处理到!!!
7. golang中根据首字母的大小写来确定可以访问的权限。无论是方法名、常量、变量名还是结构体的名称,如果首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使用
8. out chan<- int 是单向通道中的发送通道, in <-chan int 是单向通道中的接收通道
9. 无缓冲通道是缓冲为0的通道,发送时必须有其他goroutine同步接收,否则会被阻塞;而缓冲为1的通道有一个大小为1的缓冲区,无须同步接收。形象的例子:无缓冲通道好比必须要你本人签收的快递,你不来他不走,进入阻塞状态;缓冲为1的通道好比你有一个容量为1的丰巢快递柜,快递员把快递放进去就可以走,但是必须取出后才能放第2个(demo可参考[buffer1channel.go](https://github.com/tcsecchen/GoLearn/blob/master/code/goroutine/buffer1Channel/buffer1channel.go))
7. json 转结构体时,同样结构体成员也必须为大写字母开头
8. golang中根据首字母的大小写来确定可以访问的权限。无论是方法名、常量、变量名还是结构体的名称,如果首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使用
9. out chan<- int 是单向通道中的发送通道, in <-chan int 是单向通道中的接收通道
10. 无缓冲通道是缓冲为0的通道,发送时必须有其他goroutine同步接收,否则会被阻塞;而缓冲为1的通道有一个大小为1的缓冲区,无须同步接收。形象的例子:无缓冲通道好比必须要你本人签收的快递,你不来他不走,进入阻塞状态;缓冲为1的通道好比你有一个容量为1的丰巢快递柜,快递员把快递放进去就可以走,但是必须取出后才能放第2个(demo可参考[buffer1channel.go](https://github.com/tcsecchen/GoLearn/blob/master/code/goroutine/buffer1Channel/buffer1channel.go))
11 changes: 11 additions & 0 deletions code/web/antdWebServer/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package main

import (
"GoLearn/code/web/antdWebServer/web/user"
"net/http"
)

func main() {
http.HandleFunc("/login", user.Login)
http.ListenAndServe(":80", nil)
}
40 changes: 40 additions & 0 deletions code/web/antdWebServer/web/user/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package user

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)

type user struct {
Username string
Password string
}

//Login 是用户登录的函数
func Login(w http.ResponseWriter, r *http.Request) {
r.ParseForm()

if r.Method == "GET" {
username := strings.Join(r.Form["username"], "")
password := strings.Join(r.Form["password"], "")
fmt.Println("username", r.Form["username"])
fmt.Println("password", r.Form["password"])
if username == "chen" && password == "123456" {
fmt.Fprintf(w, "<h1>登录成功!</h1>")
}
} else if r.Method == "POST" {
result, _ := ioutil.ReadAll(r.Body)
r.Body.Close()
fmt.Printf("%s\n", result)
var s user
err := json.Unmarshal(result, &s)
if err != nil {
fmt.Println(err)
}
fmt.Println(s)
}

}
149 changes: 149 additions & 0 deletions code/web/baseWebserver/webserver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package main

import (
"database/sql"
"fmt"
"html/template"
"net/http"
"strconv"
"strings"

_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func parseForm(val []string) string {
return strings.Join(val, "")
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
//fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
//fmt.Println("path", r.URL.Path)
//fmt.Println("scheme", r.URL.Scheme)
//fmt.Println(r.Form["url_long"])

//模版字符串
tmpl := `<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Go Web Programming</title>
</head>
<body>
<div>
{{ range $key, $value := .}}
<h1>key:{{ $key }}</h1>
<h2>value:{{ parseForm $value}}</h2>
{{ end }}
</div>
</body>
</html>`

funcMap := template.FuncMap{"parseForm": parseForm}
t := template.New("layout.html").Funcs(funcMap) //创建模版对象
t, _ = t.Parse(tmpl) //加载模版字符串
fmt.Println(t.Name())
t.Execute(w, r.Form)

for k, v := range r.Form {
fmt.Println("key:", k)
querydata := strings.Join(v, "")
fmt.Println("val:", querydata)
if k == "url_long" {
str := sql_query(querydata)
fmt.Fprintf(w, "查询数据:")
for _, val := range str {
fmt.Fprintf(w, " %s ", val)
}

data := sql_query_all()
fmt.Fprintf(w, "<div><br/>全部数据:</div>")
for _, val := range data {
fmt.Fprintf(w, "<div> %s </div>", val)
}
} else if k == "range" {
for i := 0; i <= 1000; i++ {
fmt.Fprintln(w, i)
}
} else {
s := strings.Split(querydata, " ")
id, _ := strconv.ParseInt(s[0], 10, 32)
result := sql_insert(id, s[1], s[2])
if result {
fmt.Fprintf(w, "<br/><div>数据插入成功</div><br/>")
} else {
fmt.Fprintf(w, "<br/><div>数据插入失败</div><br/>")
}

}
}

// fmt.Fprintf(w, "<div> Hello astaxie! </div>") //这个写入到w的是输出到客户端的
}

//sql查询
func sql_query(queryData string) []string {
s := []string{"hello", "hi", "nihao"}

var err error
rows, err := db.Query("SELECT user_id,first_name,last_name FROM users where first_name=?", queryData)
if err == nil {
fmt.Println("查询数据:")
for rows.Next() {
var user_id, first_name, last_name string
err := rows.Scan(&user_id, &first_name, &last_name)
if err == nil {
fmt.Println(user_id, first_name, last_name)
s[0] = user_id
s[1] = first_name
s[2] = last_name
}
}
}
return s
}

func sql_query_all() []string {
var s []string

var err error
rows, err := db.Query("SELECT user_id,first_name,last_name FROM users")
if err == nil {
fmt.Println("全部数据:")
for rows.Next() {
var user_id, first_name, last_name string
err := rows.Scan(&user_id, &first_name, &last_name)
if err == nil {
data := user_id + " " + first_name + " " + last_name
fmt.Println(data)
s = append(s, data)
}
}
}
return s
}

func sql_insert(id int64, firstName string, lastName string) bool {
result, err := db.Exec("INSERT INTO users(user_id,first_name,last_name) VALUES (?,?,?)", id, firstName, lastName)
if err == nil {
fmt.Println(result)
return true
} else {
fmt.Println(err)
return false
}
}

func main() {
var err error
db, err = sql.Open("mysql", "root:iloveu@/dvwa")
err = db.Ping()
if err == nil {
fmt.Println("数据库已连接")
}

http.HandleFunc("/", sayhelloName)
http.ListenAndServe(":8080", nil)

}
143 changes: 0 additions & 143 deletions code/web/webserver.go

This file was deleted.

0 comments on commit 7328867

Please sign in to comment.