golangが持参したnet/httpパッケージを使って簡単なhttpサービスを書く


依存第三包:mysqlダウンロード依存:go get github.com/go-sql-driver/mysql
ディレクトリ構造:myHttpServer/├-content‖├-index.html │   ├── login.html │   └── success.html └── http01 └── httpServer.go
このHttpServerには、次の機能があります.1.トップページアクセス機能2.ユーザログイン認証機能3.データベースのCURD機能
必要なテーブルを作成するには、次の手順に従います.
user_tb | CREATE TABLE `user_tb` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) DEFAULT NULL,
  `password` varchar(300) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(3) DEFAULT NULL,
  `phone` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

次に、今回の実践に必要なhtmlファイルを3つ示します.
index.html
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>  </title>
</head>
<body>
    olang   HttpServer
</body>
</html>

login.html
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>    </title>
</head>
<body>
<form action="/loginForm" method="post">
    <span>{{.}}</span>
    username:<input type="text" name="username"/><br/>
    password:<input type="password" name="password"/><br/>
    <input type="submit" value="  "/>&nbsp;&nbsp;
    <input type="reset" value="  "/>
</form>
</body>
</html>


 success.html
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>    </title>
</head>
<body>
  {{.Username.String}}  
</body>
</html>

httpServerコード構築:
package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql" 
	"html/template"
	"io/ioutil"
	"net/http"
	"strconv"
)

//              ,           
var Db *sql.DB

func init() { //   db  
	var err error
	dsn := "root:abc@198920@tcp(localhost:3306)/golang"
	Db, err = sql.Open("mysql", dsn)
	if err != nil {
		fmt.Printf("init db instance falied:%v
"
, err) return } } type User struct { Id int `db:"id",json:"id"` Username string `db:"username",json:"username"` //sql.NullString Password string `db:"password",json:"password"` //sql.NullString Age int `db:"age",json:"age"` //sql.NullInt64 Sex string `db:"sex",json:"sex"` //sql.NullString Phone string `db:"phone",json:"phone"` //sql.NullString } /** * */ func addUser(user *User) int64 { sqlStr := "INSERT INTO user_tb(username,password,age,sex,phone) VALUES(?,?,?,?,?)" stmt, err := Db.Prepare(sqlStr) if err != nil { fmt.Printf("Prepare insert sql failed:%v
"
, err) return -1 } defer closeStmt(stmt) result, err := stmt.Exec(user.Username, user.Password, user.Age, user.Sex, user.Phone) if err != nil { fmt.Printf("exec sql failed:%v
"
, err) return -1 } lastId, err := result.LastInsertId() if err != nil { fmt.Printf("get lastId failed:%v
"
, err) return -1 } return lastId } // func updateUser(u User) int64 { updateSql := "UPDATE user_tb SET username=?,password=?,age=?,sex=?,phone=? where id=?" stmt, err := Db.Prepare(updateSql) if err != nil { fmt.Printf("Prepare update sql failed:%v
"
, err) return -1 } defer closeStmt(stmt) result, err := stmt.Exec(u.Username, u.Password, u.Age, u.Sex, u.Phone, u.Id) if err != nil { fmt.Printf("exec sql failed:%v
"
, err) return -1 } affectedId, err := result.RowsAffected() if err != nil { fmt.Printf("get affected id failed:%v
"
, err) return -1 } return affectedId } // id func delUser(id int) int64 { delSql := "DELETE FROM user_tb WHERE id=?" result, err := Db.Exec(delSql, id) if err != nil { fmt.Printf("exec del failed:%v
"
, err) return -1 } affectedId, err := result.RowsAffected() if err != nil { fmt.Printf("get affected id failed:%v
"
, err) return -1 } return affectedId } // func findUserByUsername(username string) (err error, user User) { sqlStr := "SELECT * FROM user_tb WHERE username=?" row := Db.QueryRow(sqlStr, username) err = row.Scan(&user.Id, &user.Username, &user.Password, &user.Age, &user.Sex, &user.Phone) if err != nil { return } return } // ID func findUserById(id int) (err error, user User) { sqlStr := "SELECT * FROM user_tb WHERE id=?" stmt, err := Db.Prepare(sqlStr) defer closeStmt(stmt) row := stmt.QueryRow(id) err = row.Scan(&user.Id, &user.Username, &user.Password, &user.Age, &user.Sex, &user.Phone) if err != nil { return } return } // func findUserByUsernameAndPassword(username string, password string) (err error, user User) { sqlStr := "SELECT * FROM user_tb WHERE username=? AND password=?" row := Db.QueryRow(sqlStr, username, password) err = row.Scan(&user.Id, &user.Username, &user.Password, &user.Age, &user.Sex, &user.Phone) if err != nil { return } return } // func findAllUsers() (err error, users []*User) { sqlStr := "SELECT * FROM user_tb" rows, err := Db.Query(sqlStr) if err != nil { return } defer closeRow(rows) for rows.Next() { var u User err = rows.Scan(&u.Id, &u.Username, &u.Password, &u.Age, &u.Sex, &u.Phone) if err != nil { return } users = append(users, &u) } return } // stmt func closeStmt(stmt *sql.Stmt) { if stmt != nil { fmt.Printf("close stmt connection
"
) stmt.Close() } } // row func closeRow(rows *sql.Rows) { if rows != nil { fmt.Printf("close rows connection
"
) rows.Close() } } // http var contentPath = "/Users/mengfanzhen/go/src/myHttpServer/content/" func indexPage(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles(contentPath + "index.html") if err != nil { fmt.Fprintf(w, "load index.html failed:%v
"
, err) return } t.Execute(w, nil) } func login(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles(contentPath + "login.html") if err != nil { fmt.Fprintf(w, "load login.html failed:%v
"
, err) return } t.Execute(w, nil) } // func loginForm(w http.ResponseWriter, r *http.Request) { method := r.Method if method == "POST" { r.ParseForm() // usernmae := r.FormValue("username") password := r.FormValue("password") err, user := findUserByUsernameAndPassword(usernmae, password) if err != nil { fmt.Printf("find user failed:%v
"
, err) t, err := template.ParseFiles(contentPath + "login.html") if err != nil { fmt.Fprintf(w, "load login.html failed:%v", err) return } t.Execute(w, " , ") return } t, err := template.ParseFiles(contentPath + "success.html") if err != nil { fmt.Fprintf(w, "load success.html failed:%v", err) return } t.Execute(w, user) } } // func update(w http.ResponseWriter, r *http.Request) { r.Header.Add("Content-Type", "application/json") boday, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintf(w, "read body failed:%v", err) return } var user User err = json.Unmarshal(boday,&user) if err != nil { fmt.Fprintf(w,"{\"error\":\"%v\"}",err) return } fmt.Printf("%#v
"
, user) rowId := updateUser(user) fmt.Fprintf(w, "{\"status\":\"ok\",\"affectedId\":\"%d\"}",rowId) } // func add(w http.ResponseWriter, r *http.Request) { r.Header.Add("Content-Type", "application/json") boday, err := ioutil.ReadAll(r.Body) // body if err != nil { fmt.Fprintf(w, "read body failed:%v", err) return } var user User err = json.Unmarshal(boday,&user) // user if err != nil { fmt.Fprintf(w,"{\"error\":\"%v\"}",err) return } fmt.Printf("%#v
"
, user) rowId := addUser(&user) fmt.Fprintf(w, "{\"status\":\"ok\",\"rowId\":\"%d\"}",rowId) } // func findById(w http.ResponseWriter, r *http.Request){ idStr := r.URL.Query().Get("id") id,err := strconv.Atoi(idStr) if err != nil { fmt.Fprintf(w,"parse id string to int failed:%v",err) return } err,user := findUserById(id) if err != nil { fmt.Fprintf(w,"get user by %d failed:%v",id,err) return } data,err := json.Marshal(&user) // user struct if err != nil { fmt.Fprintf(w,"parse user data struct failed:%v",err) return } fmt.Fprintf(w,string(data)) } // func findAll(w http.ResponseWriter, r *http.Request){ err,user := findAllUsers() if err != nil { fmt.Fprintf(w,"get user failed:%v",err) return } data,err := json.Marshal(&user) // user struct if err != nil { fmt.Fprintf(w,"parse user data struct failed:%v",err) return } fmt.Fprintf(w,string(data)) } func main() { // http.HandleFunc("/", indexPage) http.HandleFunc("/index", indexPage) http.HandleFunc("/login", login) http.HandleFunc("/loginForm", loginForm) http.HandleFunc("/add", add) http.HandleFunc("/update", update) http.HandleFunc("/findById",findById) http.HandleFunc("/findAll",findAll) // err := http.ListenAndServe(":9090", nil) if err != nil { fmt.Printf("Listen 9090 port failed:%v
"
, err) return } }

トップページへのアクセス:http://127.0.0.1:9090/ 使用golang自带的net/http包写一个简单的http服务_第1张图片
ログイン検証:使用golang自带的net/http包写一个简单的http服务_第2张图片
使用golang自带的net/http包写一个简单的http服务_第3张图片
使用golang自带的net/http包写一个简单的http服务_第4张图片
使用golang自带的net/http包写一个简单的http服务_第5张图片